ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 模拟GUI事件 QTestLib发送内部Qt事件,而不是模拟本地窗口系统事件,因此运行测试程序不会对机器产生任何副作用 测试文件: 与数据测试不同,需要引入 `QtGuid` ``` #include <QtGui> #include <QtTest/QtTest> class TestGui: public QObject { Q_OBJECT private slots: void testGui(); }; void TestGui::testGui() { QLineEdit lineEdit; // 模拟按键,输入 hello word,可以指定延迟时间 QTest::keyClicks(&lineEdit, "hello world"); QCOMPARE(lineEdit.text(), QString("hello world")); } ``` ## 批量测试 ``` 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"; // 先点击a,在点击backspace 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); } ```