需求

qt 如何进行 gui 单元测试高级特性

解决

测试焦点

使用焦点时需要考虑的重要一点是,在小部件上简单地调用 QWidget::setFocus 将不起作用,因为在执行测试期间小部件不可见。我们需要做的是在我们正在测试的 QWidget 上调用静态函数 QApplication::setActiveWindow

void TestPanelConcat::TestFocus()
{
  // enables focus and widget events
  QApplication::setActiveWindow(&panel);

  // set initial focus
  panel.mInputA->setFocus();
  QVERIFY2(panel.mInputA->hasFocus(), "Input A doesn't have focus");

  // write STR1
  QTest::keyClicks(QApplication::focusWidget(), STR1);
  // move focus to next widget
  QTest::keyClick(&panel, Qt::Key_Tab);
  QVERIFY2(panel.mInputB->hasFocus(), "Input B doesn't have focus");
  // write STR2
  QTest::keyClicks(QApplication::focusWidget(), STR2);
  // move focus to next widget
  QTest::keyClick(&panel, Qt::Key_Tab);
  QVERIFY2(panel.mButtonConcat->hasFocus(), "Button CONCAT doesn't have focus");
  // press button CONCAT using space
  QTest::keyClick(QApplication::focusWidget(), Qt::Key_Space);
  QCOMPARE(panel.mLabelRes->text(), STR_RES);

  // move focus to next widget
  QTest::keyClick(&panel, Qt::Key_Tab);
  QVERIFY2(panel.mButtonCancel->hasFocus(), "Button CANCEL doesn't have focus");
  // press button CANCEL using space
  QTest::keyClick(QApplication::focusWidget(), Qt::Key_Space);
  QVERIFY2(panel.mInputA->text().isEmpty(), "Cancel didn't work on input A");
  QVERIFY2(panel.mInputB->text().isEmpty(), "Cancel didn't work on input B");
  QVERIFY2(panel.mLabelRes->text().isEmpty(), "Cancel didn't work on res label");
}

测试信号

使用 QSignalSpy 类来进行测试。 先创建,然后模拟按键再检查信号数量和具体的数据。

void TestPanelConcat::TestSignals()
{
  // set input
  panel.mInputA->setText(STR1);
  panel.mInputB->setText(STR2);
  // create spy objects
  QSignalSpy spy1(&panel, &PanelConcat::DataAvailable);
  QSignalSpy spy2(&panel, &PanelConcat::DataCleared);

  // click button CONCAT
  QTest::mouseClick(panel.mButtonConcat, Qt::LeftButton);
  QCOMPARE(spy1.count(), 1);
  QCOMPARE(spy2.count(), 0);
  QList args = spy1.takeFirst();
  QCOMPARE(args.at(0).toString(), STR_RES);

  // click button CANCEL
  QTest::mouseClick(panel.mButtonCancel, Qt::LeftButton);
  QCOMPARE(spy1.count(), 0);
  QCOMPARE(spy2.count(), 1);
  args = spy2.takeFirst();
  QVERIFY2(args.empty(), "DataCleared signal has parameters now?!?");
}

上面只是示例测试了两个信号,实际使用中,一个测试一个信号。

其他

默认情况下,运行项目将启动示例应用程序。要运行单元测试,您可以更改活动运行配置,使用测试面板或使用菜单 工具 > 测试 > 运行所有测试

参考