How to test class with signals with QTest and QSignalSpy
-
I try to test my own class using QTest and QSignalSpy how it was advised here.
But I have a problem. The signals are emitted after the test is completed. Here is the test method:
void Test_AsyncSocket::testAsyncSocket() { QFETCH(QByteArray, message); QFETCH(int, responseSize); // the signal dataReady emits every time the socket buffer has requested data QSignalSpy spy(socket, SIGNAL(dataReady(QByteArray))); socket->send(message, responseSize); // I try it here but it did not help // QTest::qSleep(2000); qDebug() << "Spy size" << spy.size(); }
I have some rows to tests, so the
testAsyncSocket
method is called some times. The log output looks like this:********* Start testing of Test_AsyncSocket ********* Config: Using QTest library 4.8.1, Qt 4.8.1 PASS : Test_AsyncSocket::initTestCase() QDEBUG : Test_AsyncSocket::testAsyncSocket(QByteArray(knownQuery)) Spy size 0 QDEBUG : Test_AsyncSocket::testAsyncSocket(QByteArray(knownQuery)) Spy size 0 PASS : Test_AsyncSocket::testAsyncSocket() PASS : Test_AsyncSocket::cleanupTestCase() Totals: 3 passed, 0 failed, 0 skipped ********* Finished testing of Test_AsyncSocket ********* slot readyRead 2048 slot readyRead 3508 slot readyRead 3900 dataReady 3900
Notice, the
Spy size
line shows the size is equal to zero.So, I do not know how to verify the signals are emitted while the test is running. Can somebody help me?
UPDATE:
readyRead and dataReady implementation:// AsyncSocket.cpp void AsyncSocket::readyRead() { qDebug() << "slot readyRead" << socket->bytesAvailable(); if (socket->bytesAvailable() == responseSize) { emit(dataReady(socket->readAll()); } } // Test_AsyncSocket.cpp void Test_AsyncSocket::dataReady(const QByteArray &data) { qDebug() << "dataReady" << data.size(); }
UPDATE2: The problem is the calling for test executing inside an event loop. So, all test cases are placed in the same event. That's why slot is called (next event) when the all test cases will complete (current event).
-
@Ratzz ,
yes, you can see it in the output:// log lines ********* Finished testing of Test_AsyncSocket ********* slot readyRead 2048 slot readyRead 3508 slot readyRead 3900 dataReady 3900 <---------- here is it
The using of
count()
gives the same result.P.S. I've added simple implementations of the signals in my question.