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

时间:2013-10-03 13:16:53

标签: c++ automation automated-tests googletest

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

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

还应该在同一输入上测试Parser的参数。

因此,我需要在测试中形成以下代码:

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

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

提前致谢。

2 个答案:

答案 0 :(得分:17)

使用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")));

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

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

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

答案 1 :(得分:0)

我在Google单元测试中添加了两个类DynamicTestInfoScriptBasedTestInfo以及RegisterDynamicTest函数。它至少需要C ++ 17(尚未分析向C ++ 11或C ++ 14的反向移植)-它允许动态创建Google单元测试/在运行时创建Google单元测试,比当前的Google API稍微简单些。

例如用法可能是这样的:

https://github.com/tapika/cppscriptcore/blob/f6823b76a3bbc0ed41b4f3cf05bc89fe32697277/SolutionProjectModel/cppexec/cppexec.cpp#L156

但这需要修改的Google测试,例如,请参见以下文件:

https://github.com/tapika/cppscriptcore/blob/f6823b76a3bbc0ed41b4f3cf05bc89fe32697277/SolutionProjectModel/logTesting/gtest/gtest.h#L819

我将尝试将更改合并到正式的Google测试库中。

我还更改了如何将测试报告给用户应用程序的方式(使用<loc>标签) 但这需要修改后的Google Studio for Visual Studio测试适配器,有关更多信息,请参见youtube视频,以获取更多解释。

https://www.youtube.com/watch?v=-miGEb7M3V8

使用更新的GTA,您可以在测试资源管理器中获得文件系统列表,例如:

enter image description here