zen*_*n2k 4 c++ qt unit-testing signals-slots qt5
我正在尝试在基于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
Run Code Online (Sandbox Code Playgroud)
我希望我的测试运行得更快.如果交易失败,如何wait()在failed()发出信号后中断此呼叫?
我没有在QSignalSpy类中看到任何可用的插槽.
我应该使用QEventLoop代替?
您可能不得不使用循环并手动调用,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);
Run Code Online (Sandbox Code Playgroud)
解决方案QTestEventLoop:
QTestEventLoop loop;
QObject::connect(transaction, SIGNAL(succeeded()), &loop, SLOT(exitLoop()));
QObject::connect(transaction, SIGNAL(failed()), &loop, SLOT(exitLoop()));
transaction->run();
loop.enterLoopMSecs(3000);
Run Code Online (Sandbox Code Playgroud)
使用计时器和解决方案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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3411 次 |
| 最近记录: |