如何从 QtCreator 运行 qtestlib 单元测试
我正在 Qt Creator 中开发一个 GUI 应用程序,并想为其编写一些单元测试。
我按照 本指南 使用 QtTestlib 进行一些单元测试,并且程序编译良好。 但我该如何运行它们呢?我希望它们在调试构建时在 GUI 应用程序启动之前运行,而在发布构建时不运行。
I am developing a GUI application in Qt Creator and want to write some unit tests for it.
I followed This guide to make some unit tests with QtTestlib and the program compiles fine.
But how do I run them? I would like them to be run before the GUI app starts if debug buid and not run if release build.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要将测试代码放入您的主项目中。您应该为单元测试创建一个单独的项目,然后构建并运行它。不要修改您的主项目来运行测试。
理想情况下,您应该设置一个构建服务器,它将自动调用您的单元测试项目并构建您的版本。您可以编写此脚本。
切勿破解您的主应用程序来运行单元测试。如果您需要进行集成级别测试(即测试程序在完全编译和集成后如何工作),您应该使用不同的集成测试框架,该框架允许您从外部脚本源测试程序。 FrogLogic 的 Squish 就是这样一个框架。
Do not put test code into your main project. You should create a separate project for your unit tests then build and run that. Do not modify your main project to run tests.
Ideally, you should have a build server set up that will automatically invoke your unit test project and build your releases. You can script this.
Never hack your main application to run your unit tests. If you need to do integration level testing (i.e. testing how the program works once it is fully compiled and integrated) you should use a different integration testing framework that allows you to test the program from an externally scripted source. FrogLogic's Squish is one such framework.
使用多个目标和预处理器标志来实现此目的:
然后进入项目窗格并通过复制“Debug”添加新目标“Test”。在“构建步骤”下,向“Make”添加一个参数,
这样测试将包含在“测试”目标中,但不包含在“调试”或“发布”目标中。
Use multiple targets and preprocessor flags to achieve this:
Then go into the projects pane and add a new target "Test" by duplicating "Debug". Under Build Steps, add an argument to Make that is
That way the test is included in the Test target, but not the Debug or Release targets.
终于弄清楚如何在启动应用程序之前运行测试。
我在测试类中添加了一个静态方法来运行测试:
在主函数中,执行以下操作:
测试结果打印在应用程序输出窗口中。
Finally figured out how to run tests before starting the app.
I added one static method in the tests class to run the tests:
In the main function, do:
The test results are printed in application output window.
Qt Creator 目前尚未明确支持运行单元测试(直到 Qt Creator 2.0beta)。因此暂时您需要手动启动测试。
如果您使用的是 cmake 这样的构建系统而不是 qmake,那么您可以尝试在构建过程本身中自动运行单元测试。不幸的是我不知道有什么方法可以用 qmake 来做到这一点。 CMake 受 Qt Creator 支持,但不如 qmake。
Qt creator does not yet explicitly support running unit tests at this time (up to Qt Creator 2.0beta). So for the time being you will need to start the tests manually.
If you are using a build system like cmake instead of qmake then you could try to run the unit tests automatically as part of the build process itself. Unfortunately I am not aware of any method to do this with qmake. CMake is supported by Qt creator, although not as well as qmake.