gpt4 book ai didi

unit-testing - 如何防止 qFatal() 中止应用程序?

转载 作者:行者123 更新时间:2023-12-05 01:17:38 26 4
gpt4 key购买 nike

我的 Qt 应用程序使用 Q_ASSERT_X,它调用 qFatal(),它(默认情况下)中止应用程序。这对应用程序来说很好,但我想在对应用程序进行单元测试时抑制这种行为。 (我正在使用 Google Test Framework 。)我在一个单独的项目中进行单元测试,静态链接到我正在测试的类。 documentation对于 qFatal() 读取:

Calls the message handler with the fatal message msg. If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the debugger.

If you are using the default message handler this function will abort on Unix systems to create a core dump. On Windows, for debug builds, this function will report a _CRT_ERROR enabling you to connect a debugger to the application.

...

To supress the output at runtime, install your own message handler with qInstallMsgHandler().

这是我的 main.cpp 文件:

#include <gtest/gtest.h>
#include <QApplication>

void testMessageOutput(QtMsgType type, const char *msg) {
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s\n", msg);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg);
break;
case QtFatalMsg:
fprintf(stderr, "My Fatal: %s\n", msg);
break;
}
}

int main(int argc, char **argv)
{
qInstallMsgHandler(testMessageOutput);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

但我的应用程序仍在断言处停止。我可以看出我的自定义处理程序正在被调用,因为运行我的测试时的输出是:

My Fatal: ASSERT failure in MyClass::doSomething: "doSomething()", file myclass.cpp, line 21 The program has unexpectedly finished.

我该怎么做才能让我的测试在断言失败时继续运行?

最佳答案

Q_ASSERT_X在进行发布构建时编译为空。

因此,对于单元测试,进行发布构建,它不会调用 qFatal。

关于unit-testing - 如何防止 qFatal() 中止应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2746924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com