开发者

UnitTest++ command line arguments

I want to use a command line argument in one of my tests. I couldn't find any example of this on the web.

TEST(SomeTest)
{
    std::string fil开发者_如何转开发e("this is some command line argument");
    CHECK(something);
}

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

Any ideas?


I think what you are looking for is the ability to specify "test input" without making a new test for each.

Say you have 3 sets of test data you want to run your test routine on. You just want to run

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

without baking the tests into the test build.

But you may as well just do it:

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();
}

Parameterizing a test means the test is no longer just a test. It's now a function rather than a unit test.


Answer

There's no real reason to test command-line arguments directly. Instead, write your unit tests to check the behavior of your code (functions and classes) given different arguments. Once you are satisfied that your code is working properly under unit test, simply plug it into main and it should work properly there, as well.

Clarification

Imagine that you have your unit test on the argument to the std::string constructor.

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

Then you plug it into main.

int main(int argc, char** argv)
{
    std::string file(argv[1]);

    // do stuff....
    
    return 0;
}

Because nothing should happen to the command-line argument before it is passed to the constructor, you have effectively tested it already. If, on the other hand, your main is a mess, I would suggest refactoring that first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜