2014-09-03 63 views
1

在我的測試案例中,我想斷言qDebug()的輸出包含某個字符串。例如,這就是我的測試的樣子。注意qdebug的「綁定到UDP端口34772」輸出。我可以在我的測試函數中測試qdebug中是否存在子字符串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 ********* 

這是我的測試文件。我想在我的測試功能,檢查qDebug的輸出爲子34772.

#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" 
+2

查看'qInstallMessageHandler'。 – hyde 2014-09-03 18:50:54

回答

2

使用QTest::ignoreMessage斷言某個消息在代碼中加入待測添加QVERIFY()聲明:

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