我正在为我的应用程序开发命令行选项处理器。我决定使用GTest进行测试。它的实现已在下面简要显示:
int main(int argv, char **argv)
{
if (!ProcessOptions(argc, argv)
{
return 1;
}
// Some more code here
return 0;
}
int ProcessOptions(int argc, char **argv)
{
for (int i = 1; i < argc; ++i)
{
CheckOption(argv[i]);
CheckArgument();
if (Success)
{
EnableOption();
}
}
}
代码按预期运行,但是问题是:我想通过使用GTest提供不同的选项(有效和无效)来对其进行测试。 GTest手册内容如下:The
::testing::InitGoogleTest()
function parses the command line for googletest flags, and removes all recognized flags. This allows the user to control a test program's behavior via various flags, which we'll cover in the AdvancedGuide. You must call this function before callingRUN_ALL_TESTS()
, or the flags won't be properly initialized.
但是通过这种方式,我将只能测试一个序列。我想针对不同的选项多次执行此操作。我怎么做?
有没有更好的策略来实现这一目标?我可以使用测试治具吗?
最佳答案
您考虑过value-parameterized test吗?它们听起来很适合您的情况:
Value-parameterized tests allow you to test your code with different parameters without writing multiple copies of the same test. This is useful in a number of situations, for example:
- You have a piece of code whose behavior is affected by one or more command-line flags.
- You want to test different implementations of an OO interface.
- You want to make sure your code performs correctly for various values of those flags.
您可以编写一个或多个测试来定义命令行参数解析器的预期行为,然后以这种方式将命令行标志传递给它。
完整的代码示例显示在Google Test GitHub文档的链接中,但这是一个简短的概述:
testing::TestWithParam<T>
的测试类。 TEST_P
及其中的GetParam()
方法访问参数值。 INSTANTIATE_TEST_SUITE_P
实例化测试。使用testing::Values
方法提供值。 关于c++ - 如何使用GTest测试命令行选项解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63051440/