QSignalSpy等待和两个信号

5

我正在尝试为一个基于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

我希望我的测试运行更快。

在事务失败的情况下,如何在发出信号failed()后中断此wait()调用?

我没有在QSignalSpy类中看到任何可用的插槽。

我应该使用QEventLoop吗?


如果您在不带参数的情况下调用spy.wait(),它将在5000毫秒内发出信号后立即返回true。您无需等待5000毫秒。 - Kahn
2个回答

8

您可能需要使用循环,并在没有发出任何信号时手动调用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);

6
使用 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);

如果发出 suceeded()failed() 的代码已经依赖于 Qt 的事件循环,我认为这种方法不会起作用。你没有使用 Qt 的事件循环吗? - Mitch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接