c++ - 如何使用GTest测试命令行选项解析器

标签 c++ parsing googletest

我正在为我的应用程序开发命令行选项处理器。我决定使用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 calling RUN_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/

    相关文章:

    c++ - 插入运算符的非成员函数形式

    c++ - 我怎样才能摆脱 gtest 编译器警告 C4800 ('int' : forcing value to bool 'true' or 'false' ")

    c++ - 如何断言谷歌测试中的执行时间?

    c++ - SQL Server native 客户端 API 示例

    c++ - 我的 qmake 条件语句有什么问题?

    xml - CFXML - 当enablecfoutputonly为 "Premature end of file"时为 "yes"

    Python 使用 Beautiful Soup 对特定内容进行 HTML 处理

    c++ - 如何在 Visual Studio 中对 main() 进行单元测试

    c++ - C/C++ 中的可移植无符号长整型

    parsing - 在 PARSE 方言中,如何查找 TO 或 THRU CHARSET?