You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Qt GUI测试的QTEST_MAIN传递参数?

常规Qt GUI测试的CMake配置与代码实现

CMakeLists.txt 配置

cmake_minimum_required(VERSION 3.16)
project(QtGuiTest)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(Qt6 REQUIRED COMPONENTS Core Widgets Test)
qt_standard_project_setup()

add_executable(gui_test
    foo_test.cpp
)

target_link_libraries(gui_test PRIVATE
    Qt6::Core
    Qt6::Widgets
    Qt6::Test
)

# 启用测试套件
enable_testing()
add_test(NAME gui_test COMMAND gui_test)

测试代码 foo_test.cpp

#include <QTest>
#include <QWidget>

class Foo : public QObject
{
    Q_OBJECT
private slots:
    void testGuiBasics()
    {
        QWidget widget;
        widget.show();
        QVERIFY(widget.isVisible());
        QCOMPARE(widget.windowTitle(), QString(""));
    }
};

QTEST_MAIN(Foo)
#include "foo_test.moc"

实现CMake参数传递到Qt测试类

要通过cmake -D TEST_MSG=world传递参数并让测试类Foo以std::string类型获取,只需通过编译宏将CMake变量注入代码即可,具体实现如下:

调整后的CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project(QtGuiTestWithParam)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# 设置默认参数,若未通过cmake传入则使用"default"
if(NOT DEFINED TEST_MSG)
    set(TEST_MSG "default")
endif()

find_package(Qt6 REQUIRED COMPONENTS Core Widgets Test)
qt_standard_project_setup()

add_executable(gui_test_with_param
    foo_test_with_param.cpp
)

# 将CMake参数转为编译宏,添加引号确保代码中识别为字符串字面量
target_compile_definitions(gui_test_with_param PRIVATE
    TEST_MSG="${TEST_MSG}"
)

target_link_libraries(gui_test_with_param PRIVATE
    Qt6::Core
    Qt6::Widgets
    Qt6::Test
)

enable_testing()
add_test(NAME gui_test_with_param COMMAND gui_test_with_param)

调整后的测试代码 foo_test_with_param.cpp

#include <QTest>
#include <QWidget>
#include <string>

class Foo : public QObject
{
    Q_OBJECT
private:
    std::string test_msg;
private slots:
    // 测试前初始化:从编译宏读取参数
    void initTestCase()
    {
        test_msg = std::string(TEST_MSG);
    }

    void testParamValidation()
    {
        qDebug() << "Received test message:" << QString::fromStdString(test_msg);
        QVERIFY(!test_msg.empty());
        // 示例:验证传入的参数是否符合预期
        QCOMPARE(test_msg, std::string("world"));
    }

    void testGuiWithParam()
    {
        QWidget widget;
        // 使用参数配置GUI属性
        widget.setWindowTitle(QString::fromStdString(test_msg));
        widget.show();
        QVERIFY(widget.isVisible());
        QCOMPARE(widget.windowTitle(), QString::fromStdString(test_msg));
    }
};

QTEST_MAIN(Foo)
#include "foo_test_with_param.moc"

编译与运行步骤

  1. 创建并进入构建目录:
mkdir build && cd build
  1. 传递参数执行CMake配置:
cmake -D TEST_MSG=world ..
  1. 编译项目:
make # 或根据生成器使用ninja/msbuild等
  1. 运行测试:
./gui_test_with_param

内容的提问来源于stack exchange,提问作者fghoussen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:53:21