本文介绍了使用 Qt 的 QTestLib 模块进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用 Qt 的单元测试系统编写一些测试.

I started writing some tests with Qt's unit testing system.

您通常如何组织测试?每个模块类是一个测试类,还是使用单个测试类测试整个模块?Qt 文档建议遵循前一种策略.

How do you usually organize the tests? It is one test class per one module class, or do you test the whole module with a single test class? Qt docs suggest to follow the former strategy.

我想为一个模块编写测试.模块只提供了一个类将被模块用户使用,但是在其他类中抽象了很多逻辑,我也想测试一下,除了测试公共类.

I want to write tests for a module. The module provides only one class that is going to be used by the module user, but there is a lot of logic abstracted in other classes, which I would also like to test, besides testing the public class.

问题在于 Qt 提出的运行测试的方法涉及 QTEST_MAIN 宏:

The problem is that Qt's proposed way to run tests involved the QTEST_MAIN macro:

QTEST_MAIN(TestClass)
#include "test_class.moc"

最终一个测试程序只能测试一个测试类.为模块中的每个类创建测试项目有点糟糕.

and eventually one test program is capable of testing just one test class. And it kinda sucks to create test projects for every single class in the module.

当然,可以查看QTEST_MAIN 宏,重写它,然后运行其他测试类.但是有什么东西可以开箱即用吗?

Of course, one could take a look at the QTEST_MAIN macro, rewrite it, and run other test classes. But is there something, that works out of the box?

到目前为止我都是手工制作的:

So far I do it by hand:

#include "one.h"
#include "two.h"

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    TestOne one;
    QTest::qExec(&one, argc, argv);
    TestOne two;
    QTest::qExec(&two, argc, argv);
}

推荐答案

是的,QTest 强制有点奇怪的测试结构,通常不如 Google Test/Mock Framework.对于一个项目,我不得不使用 QTest(客户要求),这是我的使用方法:

Yeah, QTest forces bit strange test structure and is generally inferior to Google Test/Mock Framework. For one project I'm forced to use QTest (client requirement), and here's how I use it:

  1. 我将所有测试编译为一个子目录模板项目
  2. 为了更轻松地创建新测试,我通过使用每个测试 .pro 文件中包含的 common.pri 文件共享了许多项目配置
  3. 如果可能,我共享目标文件目录以加快编译
  4. 我使用批处理+awk+sed 脚本运行它们.

设置这四点非常容易,并且使 QTest 的使用变得非常愉快.您是否在运行多个测试时遇到上述配置无法解决的问题?

Setting up this four points is very easy and makes usage of QTest almost pleasant. Do you have some problems with running multiple tests that are not solved by the config described above?

PS:按照您的方式运行测试,即调用多个 QTest::qExec 会导致 -o 命令行开关出现问题 - 您只会获得最后一个测试类的结果.

PS: running tests the way you do, i.e. calling multiple QTest::qExec causes problems with -o command line switch - you'll get only results for the last tested class.

这篇关于使用 Qt 的 QTestLib 模块进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 06:54