【问题标题】:UnitTest++ command line argumentsUnitTest++ 命令行参数
【发布时间】:2011-09-26 04:30:26
【问题描述】:

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

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

int main(int argc, char** argv)
{
    return UnitTest::RunAllTests();
}

有什么想法吗?

【问题讨论】:

  • 编写良好的单元测试是自包含的,因此不依赖于命令行参数。您应该尝试对其进行重组。
  • 命令行参数有点违背了单元测试的目的......
  • 我认为 OP 想要在指定文件上运行单元测试执行的测试例程。 TEST(fileLoaderStressTest) { results* results = fileLoader("want to arg-select what the data-file is"); CHECK(results.valid); }这是对单元测试的某种无效使用吗?

标签: c++ unit-testing unittest++


【解决方案1】:

我认为您正在寻找的是能够指定“测试输入”而无需为每个输入进行新测试。

假设您有 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();
}

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

【讨论】:

    【解决方案2】:

    回答

    没有真正的理由直接测试命令行参数。相反,编写单元测试来检查给定不同参数的代码(函数和类)的行为。一旦您对您的代码在单元测试下正常工作感到满意,只需将其插入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 是一团糟,我建议先重构它。

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2011-02-25
      • 2013-02-14
      相关资源
      最近更新 更多