UnitTest++命令行参数

UnitTest++ command line arguments

本文关键字:参数 命令行 UnitTest++      更新时间:2023-10-16

我想在一个测试中使用命令行参数。我在网上找不到任何这样的例子。

TEST(SomeTest)
{
    std::string file("this is some command line argument");
    CHECK(something);
}
int main(int argc, char** argv)
{
    return UnitTest::RunAllTests();
}

有什么想法吗?

我认为您想要的是指定"测试输入"的能力,而无需为每个输入进行新的测试。

假设你有3组测试数据要运行你的测试例程。你只想运行

./unittest_build SomeTest file1
./unittest_build SomeTest file2
./unittest_build SomeTest file3

而无需将测试烘焙到测试构建中。

但你也可以这么做:

void runCheck(const std::string& filename) {
    std::string file(filename);
    // well, you're gonna do stuff here
    CHECK(something);
}
TEST(SomeTest)
{
    runCheck(std::string("your first testing datafile"));
    runCheck(std::string("your second testing datafile"));
    runCheck(std::string("your third testing datafile"));
    // this is what your test is. It tests these files. 
}
int main(int argc, char** argv)
{
    return UnitTest::RunAllTests();
}

参数化测试意味着测试不再只是一个测试。它现在是一个函数,而不是一个单元测试。

答案

没有真正的理由直接测试命令行参数。相反,编写单元测试来检查给定不同参数的代码(函数和类)的行为。一旦您对您的代码在单元测试中正常工作感到满意,只需将其插入main,它也应该在那里正常工作。

澄清

假设您对std::string构造函数的参数进行了单元测试。

TEST(SomeTest)
{
    std::string file("this is some command line argument");
    CHECK(something);
}

然后将其插入main

int main(int argc, char** argv)
{
    std::string file(argv[1]);
    // do stuff....
    
    return 0;
}

因为在将命令行参数传递给构造函数之前,它不应该发生任何事情,所以您已经对其进行了有效的测试。另一方面,如果您的main一团糟,我建议您首先进行重构。