添加测试
测试基于 C++ 的Qt Creator 插件代码主要有两种方法:
这两种方法各有其特定的使用场景和配置,将在以下各节中进行说明。
配置 CMake
在添加测试之前,请先准备好您的构建文件。这些文件需要识别QtTest 依赖项,并包含一个用于带测试构建插件的CMake选项:
# Add a CMake option that enables building your plugin with tests.
# You don't want your released plugin binaries to contain tests,
# so make that default to 'NO'.
# Enable tests by passing -DWITH_TESTS=ON to CMake.
option(WITH_TESTS "Builds with tests" NO)
if(WITH_TESTS)
# Look for QtTest
find_package(${QtX} REQUIRED COMPONENTS Test)
# Tell CMake functions like add_qtc_plugin about the QtTest component.
set(IMPLICIT_DEPENDS Qt::Test)
# Enable ctest for auto tests.
enable_testing()
endif()插件测试
插件测试与您的插件及其与Qt Creator 的交互深度集成。若要为需要预先配置Qt Creator 基础设施或您的插件的功能添加测试,请编写插件测试。
通过在Qt Creator 中添加-test <pluginname> 命令行参数来执行插件测试。此时,Qt Creator 会完全加载您的插件及其所有依赖插件,并经历正常的插件生命周期。待您的插件及所有依赖项完全初始化后,测试将开始执行。随后,Qt Creator 会自动关闭。 因此,您的插件测试可以访问所有被您的插件所依赖的Qt Creator 插件所导出的功能,例如Core::ICore 。请使用QtTest 提供的常规测试宏,如QVERIFY 或QCOMPARE 来报告测试的成功或失败。
要添加插件测试,请创建一个基于QObject 的类,其中包含用于测试的私有槽,并在插件的ExtensionSystem::IPlugin::initialize() 方法中通过ExtensionSystem::IPlugin::addTest() 将其注册。请使用WITH_TESTS 检查来保护所有与测试相关的代码,以避免在插件的二进制发布版本中包含测试函数。
包含QtTest :
#ifdef WITH_TESTS #include <QtTest> #endif
然后实现测试函数:
#ifdef WITH_TESTS class MyPluginTests : public QObject { Q_OBJECT private slots: void testMyTest() { // a failing test QVERIFY(false); } }; #endif
在ExtensionSystem::IPlugin::initialize() 中注册您的测试:
#ifdef WITH_TESTS addTest<MyPluginTests>(); #endif
如果您像本示例一样在源文件中声明了测试对象,还需包含.moc 文件,这是 Qt Meta-Object Compiler 所必需的:
#ifdef WITH_TESTS #include "example.moc" #endif
自动测试
若要添加一个不依赖于正在运行的Qt Creator 基础设施的测试,请使用独立于插件接口的自动测试。解析器是一个常见的例子,但只要以模块化方式编写,您就可以通过这种方式测试许多内容。
尽管您的测试并不位于插件接口中(与插件测试不同),但您仍可将测试与库以及您的插件库本身进行链接,以避免代码重复或重复编译。
原则上您可以使用任何自动测试框架,但QtTest 是一个与 Qt 集成良好的简单框架,且也被用于插件测试。
要添加测试,请添加测试的 C++ 文件,并在 CMake 文件中使用add_qtc_test 来添加测试目标。如果您的测试使用了插件库,请使用DEPENDS 将其作为依赖项添加。
在下面的示例中,该插件导出函数addOne :
#pragma once #include "example_global.h" namespace Example { int EXAMPLE_EXPORT addOne(int i); } // namespace Example
并在源文件中实现该函数:
int addOne(int i) { return i; // that is wrong! }
测试通过DEPENDS 与插件库目标进行链接:
# conditionally add auto tests
if(WITH_TESTS)
add_qtc_test(tst_mytest
SOURCES tst_mytest.cpp
DEPENDS Example
)
endif()基于QtTest 的测试随后会包含该插件的头文件,并测试该函数:
#include "examplefunctions.h" #include <QtTest> class tst_MyTest : public QObject { Q_OBJECT private slots: void mytest(); }; void tst_MyTest::mytest() { // a failing test QCOMPARE(Example::addOne(1), 2); } QTEST_GUILESS_MAIN(tst_MyTest) #include "tst_mytest.moc"
Copyright © The Qt Company Ltd. and other contributors. 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.