Waiting for QSignalSpy and two signals

I am trying to write unit test for a class in a Qt based project (Qt 5, C ++ 03).

class Transaction { // This is just a sample class
//..
public signals:
   void succeeded();
   void failed();
}

Transaction* transaction = new Transaction(this);
QSignalSpy spy(transaction, SIGNAL(succeeded()));
transaction->run();
spy.wait(5000); // wait for 5 seconds

I want my test to run faster. How to interrupt this call wait()after a signal failed()in case of a failed transaction?

I do not see any slots available in the QSignalSpy class.

Should I use QEventLoop instead?

+4
source share
2 answers

Solution with QTestEventLoop:

QTestEventLoop loop;
QObject::connect(transaction, SIGNAL(succeeded()), &loop, SLOT(exitLoop()));
QObject::connect(transaction, SIGNAL(failed()), &loop, SLOT(exitLoop()));
transaction->run();
loop.enterLoopMSecs(3000);

Timer solution and QEventLoop:

Transaction* transaction = new Transaction(this);
QSignalSpy spy(transaction, SIGNAL(succeeded()));  
QEventLoop loop;  
QTimer timer;
QObject::connect(transaction, SIGNAL(succeeded()), &loop, SLOT(quit()));
QObject::connect(transaction, SIGNAL(failed()), &loop, SLOT(quit()));
QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
timer.start(3000);
loop.exec();
transaction->run();
QCOMPARE(spy.count(), 1);
+1
source

You may have to use a loop and manually call QTest::qWait(), while none of the signals were emitted:

QSignalSpy succeededSpy(transaction, SIGNAL(succeeded()));
QSignalSpy failedSpy(transaction, SIGNAL(failed()));
for (int waitDelay = 5000; waitDelay > 0 && succeededSpy.count() == 0 && failedSpy.count() == 0; waitDelay -= 100) {
    QTest::qWait(100);
}

QCOMPARE(succeededSpy.count(), 1);
+5
source

Source: https://habr.com/ru/post/1614558/


All Articles