第 1 章:编写单元测试
第一章将演示如何编写简单的单元测试,以及如何将测试用例作为独立的可执行文件运行。
编写测试
假设你想测试QString 类的行为。首先,您需要一个包含测试函数的类。该类必须继承于QObject :
#include <QTest> class TestQString: public QObject { Q_OBJECT private slots: void toUpper(); };
注意: 您需要包含QTest 头文件,并将测试函数声明为私有槽,以便测试框架找到并执行它。
然后,您需要实现测试函数本身。实现过程如下:
void TestQString::toUpper() { QString str = "Hello"; QVERIFY(str.toUpper() == "HELLO"); }
QVERIFY() 宏对作为参数传递的表达式进行评估。如果表达式求值为 true,则继续执行测试函数。否则,一条描述失败的消息将附加到测试日志中,测试函数停止执行。
但如果想在测试日志中输出更详细的信息,则应使用QCOMPARE() 宏:
如果字符串不相等,两个字符串的内容都会附加到测试日志中,让人一眼就能看出比较失败的原因。
准备单机可执行文件
最后,要使我们的测试用例成为独立可执行文件,需要以下两行:
QTEST_MAIN(TestQString) #include "testqstring.moc"
QTEST_MAIN() 宏扩展为一个简单的main()
方法,运行所有测试函数。请注意,如果测试类的声明和实现都在.cpp
文件中,我们还需要包含生成的 moc 文件,以使 Qt 的自省功能正常工作。
构建可执行文件
您可以使用 CMake 或 qmake 构建测试用例可执行文件。
使用 CMake 构建
在 CMakeLists.txt 文件中配置构建设置:
# Copyright (C) 2022 The Qt Company Ltd. # SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause cmake_minimum_required(VERSION 3.16) project(tutorial1 LANGUAGES CXX) find_package(Qt6 REQUIRED COMPONENTS Core Gui Test Widgets) qt_standard_project_setup() qt_add_executable(tutorial1 testqstring.cpp ) set_target_properties(tutorial1 PROPERTIES WIN32_EXECUTABLE TRUE MACOSX_BUNDLE TRUE ) target_link_libraries(tutorial1 PRIVATE Qt6::Core Qt6::Gui Qt6::Test Qt6::Widgets ) install(TARGETS tutorial1 BUNDLE DESTINATION . RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ) qt_generate_deploy_app_script( TARGET tutorial1 OUTPUT_SCRIPT deploy_script NO_UNSUPPORTED_PLATFORM_ERROR ) install(SCRIPT ${deploy_script})
然后,从命令行运行cmake
或使用Qt-prefix/<version>/<platform>/bin/qt-cmake
中的qt-cmake
方便脚本:
<Qt-prefix>/<version>/<platform>/bin/qt-cmake <source-dir> <build-dir> -G Ninja
然后,运行你喜欢的生成工具来构建可执行文件。在这里,我们使用的是 Ninja:
ninja
使用 qmake
在.pro
文件中配置编译设置:
QT += widgets testlib SOURCES = testqstring.cpp # install target.path = $$[QT_INSTALL_EXAMPLES]/qtestlib/tutorial1 INSTALLS += target
然后,运行qmake
,最后运行make
来构建可执行文件:
qmake make
注: 如果您使用的是 windows,请将make
替换为nmake
或您使用的任何构建工具。
运行可执行文件
运行生成的可执行文件会得到以下输出结果:
********* Start testing of TestQString ********* Config: Using QtTest library %VERSION%, Qt %VERSION% PASS : TestQString::initTestCase() PASS : TestQString::toUpper() PASS : TestQString::cleanupTestCase() Totals: 3 passed, 0 failed, 0 skipped ********* Finished testing of TestQString *********
恭喜!您刚刚使用Qt Test 框架编写并执行了第一个单元测试。
© 2025 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.