QSignalSpy 等待和两个信号
QSignalSpy wait and two signals
我正在尝试为基于 Qt 的项目(Qt 5、C++03)中的 class 编写单元测试。
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
我希望我的测试 运行 更快。
如果交易失败,如何在发出信号 failed()
后中断此 wait()
调用?
我在 QSignalSpy 中没有看到任何可用的插槽 class。
我应该改用 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);
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);
我正在尝试为基于 Qt 的项目(Qt 5、C++03)中的 class 编写单元测试。
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
我希望我的测试 运行 更快。
如果交易失败,如何在发出信号 failed()
后中断此 wait()
调用?
我在 QSignalSpy 中没有看到任何可用的插槽 class。
我应该改用 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);
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);