我试图为基于Qt的项目(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我要我的测试跑得更快。在事务失败时,如何在发出信号wait()后中断failed()调用?
我在QSignalSpy类中看不到任何可用的插槽。
我应该用QEventLoop代替吗?
发布于 2015-11-05 07:57:27
使用QTestEventLoop的解决方案
QTestEventLoop loop;
QObject::connect(transaction, SIGNAL(succeeded()), &loop, SLOT(exitLoop()));
QObject::connect(transaction, SIGNAL(failed()), &loop, SLOT(exitLoop()));
transaction->run();
loop.enterLoopMSecs(3000);带有计时器和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);发布于 2015-11-05 07:43:03
在没有发出信号时,您可能需要使用循环并手动调用QTest::qWait():
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);https://stackoverflow.com/questions/33538785
复制相似问题