为了测试GUI组件 ,可以使用诸如QTest::keyClick()函数,通过内部事件传递,来模拟本地窗口系统的事件。例如:

// 代码取自 http://qt.nokia.com/doc/qtestlib-tutorial4-testgui-cpp.html
#include <QtGui>
#include <QtTest/QtTest>
class TestGui: public QObject
{
  Q_OBJECT
private slots:
  void testGui_data();
  void testGui();
};
void TestGui::testGui_data()
{
  QTest::addColumn<QTestEventList>("events");
  QTest::addColumn<QString>("expected");
  // 添加按键事件
  QTestEventList list1;
  list1.addKeyClick('a');
  QTest::newRow("char") << list1 << "a";
  QTestEventList list2;
  list2.addKeyClick('a');
  list2.addKeyClick(Qt::Key_Backspace);
  QTest::newRow("there and back again") << list2 << "";
}
void TestGui::testGui()
{
  QFETCH(QTestEventList, events);
  QFETCH(QString, expected);
  QLineEdit lineEdit;
  // 模拟按键事件,并比较结果
  events.simulate(&lineEdit);
  QCOMPARE(lineEdit.text(), expected);
}
QTEST_MAIN(TestGui)
#include "testgui.moc"

  后看看如何测试benchmark

void TestQString::testBenchmark()
{
  QString str("HeLlO");
  // 以下代码被测试benchmark
  QBENCHMARK
  {
    str.toLower();
  }
}

  得到如下输出:
RESULT : TestQString::testBenchmark():
0.00062 msec per iteration (total: 41, iterations: 65536)