我使用 CppUnit 作为单元测试框架。是否可以选择要在运行时执行的测试用例子集?
CppUnit 中是否提供了过滤选项来适应这一点?
您可能在 main() 中调用的 TestRunner::run() 方法实际上具有可选参数:run(std::string testName = "", bool doWait = false, bool doPrintResult = true, bool doPrintProgress = true)。testName 必须是测试的特定名称。如果需要,您可以按名称请求特定测试。您还可以在特定测试上调用 runTest(Test*),或 runTestByName(testName)。
但听起来你想变得更复杂。假设您使用 CPPUNIT_TEST_SUITE_REGISTRATION() 宏注册了所有测试,静态 TestFactoryRegistry::makeTest() 方法将返回所有已注册测试的 TestSuite。
TestSuite 对象通过 getTests() 方法生成一个向量。您可以遍历它们,将它们的名称与正则表达式(或通过索引号或任何您想要的)进行匹配,而不是像大多数人那样在整个套件上调用 TestRunner::addTest(registry.makeTest()) ,您只需添加您要求的特定测试。
您必须编写一些东西来遍历测试并进行匹配,但除此之外它应该非常简单。大概有十几行代码,加上解析命令行参数。使用正则表达式让自己更简单。
另一种方法:
// find the unit test as specified by the one argument to this program
CPPUNIT_NS::Test *suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest();
int iTestIndex = 0;
for (; iTestIndex < suite->getChildTestCount(); ++iTestIndex)
{
fprintf(stderr, "INFO: Looking for a match between '%s' and '%s'\n",
suite->getChildTestAt(iTestIndex)->getName().c_str(),
argv[1]);
if (suite->getChildTestAt(iTestIndex)->getName() == std::string(argv[1]))
{
fprintf(stderr, "INFO: Found a match for '%s' and '%s'\n",
suite->getChildTestAt(iTestIndex)->getName().c_str(),
argv[1]);
break;
}
}
if (iTestIndex >= suite->getChildTestCount())
{
fprintf(stderr, "ERROR: Did NOT find test '%s'!\n", argv[1]);
return -1;
}