c++ - 在运行时创建测试(谷歌测试)

标签 c++ automation automated-tests googletest

我有一个解析器需要测试。这个解析器有很多测试输入文件。通过将解析器的输出与相应的预生成文件进行比较来测试解析器的预期行为。

目前我正在测试中处理 YAML 文件以获取输入文件、预期文件及其描述(如果失败,将打印此描述)。

还有一些应该在相同输入上测试的解析器参数。

所以,我需要在测试中形成如下代码:

TEST(General, GeneralTestCase)
{
   test_parameters = yaml_conf.get_parameters("General", "GeneralTestCase");
   g_parser.parse(test_parameters);

   ASSERT_TRUE(g_env.parsed_as_expected()) << g_env.get_description("General", "GeneralTestCase");
}

TEST(Special, SpecialTestCase1)
{
   test_parameters = yaml_conf.get_parameters("Special", "SpecialTestCase1");
   g_parser.parse(test_parameters);

   ASSERT_TRUE(g_env.parsed_as_expected()) << g_env.get_description("Special", "SpecialTestCase1");
}

TEST(Special, SpecialTestCase2)
{
   test_parameters = yaml_conf.get_parameters("Special", "SpecialTestCase2");
   g_parser.parse(test_parameters);

   ASSERT_TRUE(g_env.parsed_as_expected()) << g_env.get_description("Special", "SpecialTestCase2");
}

很容易看出代码的重复。所以我觉得有一种方法可以使这些测试自动化。

提前致谢。

最佳答案

使用value-parameterized tests :

typedef std::pair<std::string, std::string> TestParam;

class ParserTest : public testing::TestWithParam<TestParam> {};

TEST_P(ParserTest, ParsesAsExpected) {
   test_parameters = yaml_conf.get_parameters(GetParam().first,
                                              GetParam().second);
   g_parser.parse(test_parameters);
   ASSERT_TRUE(g_env.parsed_as_expected());
}

INSTANTIATE_TEST_CASE_P(
    GeneralAndSpecial,
    ParserTest,
    testing::Values(
        TestParam("General", "GeneralTestCase")
        TestParam("Special", "SpecialTestCase1")
        TestParam("Special", "SpecialTestCase2")));

您可以从磁盘读取测试用例列表并将其作为 vector 返回:

std::vector<TestParam> ReadTestCasesFromDisk() { ... }

INSTANTIATE_TEST_CASE_P(
    GeneralAndSpecial,  // Instantiation name can be chosen arbitrarily.
    ParserTest,
    testing::ValuesIn(ReadTestCasesFromDisk()));

关于c++ - 在运行时创建测试(谷歌测试),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19160244/

相关文章:

c++ - 如何将模板类内部的模板类用作带有模板参数的模板模板参数?

c++ - Unresolved external symbol Visual Studio 2010 错误

python - 在不使用任何浏览器的情况下使用 Selenium

javascript - Selenium WebDriver - 等待 Angular 请求(Java)

selenium - 使用 Selenium Webdriver 测试 ZK 应用程序

unit-testing - 为单元测试用例设置批量数据

c++ - _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) 在 "return 0"之后

c++ - 是否可以在不使用 ‘undef’ 的情况下重新定义宏?

automation - 停止 Microsoft Word 重新使用通过 COM Interop 创建的 WinWord.exe 进程

CSS Sprite 自动化