教程:Qt Test 应用程序
本教程介绍如何使用 Qt VS Tools 与 Microsoft 提供的单元测试资源管理器(Unit Test Explorer)来可视化和运行单元测试用例。编写测试用例。 Qt Test框架编写测试用例。
在开始之前
在开始之前,您必须
创建Qt Test 应用程序
- 转到File >New >Project 。
- 搜索 Qt Test Application.
- 选择项目向导,然后选择Next 。
- 在Project name 中,输入QtTest,然后选择OK 。
- 要确认Welcome 对话框,请选择Next 。
- 设置Debug 构建配置,并选择要包含在项目中的模块:

默认情况下会选择测试应用程序项目中通常需要的模块。
- 选择Next ,继续进入类创建页面:

- 选择Lower case filenames ,在生成的文件名中只使用小写字母。
- 选择Add .runsettings file to project 可为应用程序使用默认 .runsettings 文件。要使用解决方案范围的 .runsettings 文件,请按照测试适配器设置中的说明,添加
QtTest运行配置部分。 - 选择Finish 创建项目。
现在您有了一个可运行的Qt Test 小应用程序。转到Test >Test Explorer (或按Ctrl+E, T)打开 Visual Studio 单元测试资源管理器。
编写测试用例
使用 Qt Test 框架的函数和宏来定义测试。创建的测试程序提供了一组常用函数和一个测试函数。
#include <QtTest>class QtTest:publicQObject { Q_OBJECTprivate slots:voidinitTestCase_data() { qDebug("Creates a global test data table."); }voidinitTestCase() { qDebug("Called before the first test function is executed."); }voidinit() { qDebug("Called before each test function is executed."); }voidmyTest() { QVERIFY(true);// 检查条件是否满足QCOMPARE(1, 1);// 比较两个值}voidcleanup() { qDebug("Called after every test function."); }voidcleanupTestCase() { qDebug("Called after the last test function was executed."); } }; QTEST_MAIN(QtTest)#include "QtTest.moc"
使用单元测试资源管理器发现测试
现在你已经有了带有测试功能的测试应用程序项目,可以使用单元测试资源管理器来发现和管理测试功能。
要构建解决方案,请访问Build >Build Solution (或按Ctrl+Shift+B)。这一步至关重要,因为它会编译单元测试资源管理器发现的测试二进制文件。
单元测试资源管理器会在成功构建后自动发现测试。如果测试没有出现,请选择测试资源管理器工具栏上的Run All 或Refresh ,手动触发测试发现。

使用单元测试资源管理器运行和分析测试
在单元测试资源管理器中,选择Run All 运行所有测试。要运行特定测试或测试组,请从列表中选择它们,然后选择Run Selected Tests 。右键单击单个测试或测试组,可获得更多选项,如调试特定测试。
单元测试资源管理器会显示测试结果,显示哪些测试通过了,哪些测试失败了。对于失败的测试,选择测试名称可查看详细信息,包括错误信息和堆栈跟踪。使用 "测试资源管理器 "中的过滤和分组选项,可有效组织和管理测试结果。

通常,Qt Test 需要一个项目本地或解决方案范围内的 runsettings 文件,用于配置各种测试参数和环境。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.