在寻找同样的答案时,我从http://qtcreator.blogspot.de/2009/10/running-multiple-unit-tests.html找到了一个非常好的解决方案。他使用一个容器创建了一个命名空间,该容器注册了所有创建的测试(通过 DECLARE_TEST 宏),然后使用它来运行列表中的所有测试。我重写了它以适合我的代码,并在此处发布我的版本(我的 Qt Creator 版本:4.1.0):
/* BASED ON
* http://qtcreator.blogspot.de/2009/10/running-multiple-unit-tests.html
*/
#ifndef TESTCOLLECTOR_H
#define TESTCOLLECTOR_H
#include <QtTest>
#include <memory>
#include <map>
#include <string>
namespace TestCollector{
typedef std::map<std::string, std::shared_ptr<QObject> > TestList;
inline TestList& GetTestList()
{
static TestList list;
return list;
}
inline int RunAllTests(int argc, char **argv) {
int result = 0;
for (const auto&i:GetTestList()) {
result += QTest::qExec(i.second.get(), argc, argv);
}
return result;
}
template <class T>
class UnitTestClass {
public:
UnitTestClass(const std::string& pTestName) {
auto& testList = TestCollector::GetTestList();
if (0==testList.count(pTestName)) {
testList.insert(std::make_pair(pTestName, std::make_shared<T>()));
}
}
};
}
#define ADD_TEST(className) static TestCollector::UnitTestClass<className> \
test(#className);
#endif // TESTCOLLECTOR_H
然后,只需在测试标头中添加 ADD_TEST(class) 行,如下所示:
#ifndef TESTRANDOMENGINES_H
#define TESTRANDOMENGINES_H
#include <QtTest>
#include "TestCollector.h"
class TestRandomEngines : public QObject
{
Q_OBJECT
private Q_SLOTS:
void test1();
};
ADD_TEST(TestRandomEngines)
#endif // TESTRANDOMENGINES_H
并且要运行所有测试,只需执行以下操作:
#include "TestCollector.h"
#include <iostream>
int main(int argc, char *argv[]) {
auto nFailedTests = TestCollector::RunAllTests(argc, argv);
std::cout << "Total number of failed tests: "
<< nFailedTests << std::endl;
return nFailedTests;
}