c++ - 在测试用例中读取 qdebug?

标签 c++ qt qdebug

在我的测试用例中,我想断言 qDebug() 的输出包含某个字符串。例如,这是我的测试的样子。注意 qdebug 输出的“绑定(bind)到 UDP 端口 34772”。我可以从我的测试函数中测试子字符串 34772 是否存在于 qdebug 中吗?

********* Start testing of tst_NetSocket *********
Config: Using QTest library 4.8.6, Qt 4.8.6
PASS   : tst_NetSocket::initTestCase()
QDEBUG : tst_NetSocket::testBindToPortDefaultToMinAvailable() Bound to UDP port  34772 
FAIL!  : tst_NetSocket::testBindToPortDefaultToMinAvailable() 'socket->getCurrentPort() == port_should_be' returned FALSE. ()
   Loc: [test_net_socket.cpp(59)]
PASS   : tst_NetSocket::cleanupTestCase()
Totals: 5 passed, 1 failed, 0 skipped
********* Finished testing of tst_NetSocket *********

这是我的测试文件。我想在我的测试函数中添加一个 QVERIFY() 语句来检查子字符串 34772 的 qDebug 输出。

#include <QObject>
#include <QtTest/QtTest>
#include <unistd.h>
#include "net_socket.hpp"

class tst_NetSocket: public QObject
{
    Q_OBJECT

private slots:
    // ....
    void testBindToPortDefaultToMinAvailable();
};

// ... other tests removed for example ...

void tst_NetSocket::testBindToPortDefaultToMinAvailable()
{
    NetSocket * socket = new NetSocket();

    int port_should_be = (32768 + (getuid() % 4096)*4);
    if (socket->bindToPort()) {
        QVERIFY(socket->getCurrentPort() == port_should_be);
    }
}

QTEST_MAIN(tst_NetSocket)
#include "test_net_socket.moc"

最佳答案

使用QTest::ignoreMessage断言特定消息已添加到被测代码中:

// ...
int port_should_be = (32768 + (getuid() % 4096)*4);
QTest::ignoreMessage(QtDebugMsg, QString::fromLatin1("Bound to UDP port  %1").arg(port_should_be).toUtf8().constData());
// ...

关于c++ - 在测试用例中读取 qdebug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649449/

相关文章:

c++ - qDebug() 不打印任何东西

c++ - 错误 : missing type specifier

c++ - 未找到 difference_type

c++ - 如何使用 Qt 获取系统代理?

android - Qt 安卓 : Virtual keyboard keeps switching to uppercase when I type in a QLineEdit

c++ - QTableWidget:只允许数字

c++ - 如何保存 lambda 以供以后回调?

c++ - 在 C++ 中使用均匀实数分布生成的随机数并不是真正均匀分布的

c++ - 如何在没有附加空格和换行符的情况下调用 qDebug?