如何使用Google测试进行C 通过数据组合运行

How to use google test for C++ to run through combinations of data

本文关键字:数据 组合 运行 何使用 Google 测试      更新时间:2023-10-16

我有一个单位测试,我需要以200个可能的数据组合进行运行。(生产实现具有要在配置文件中测试的数据。我知道如何模拟这些值)。我更喜欢为每种组合编写单独的测试用例,并使用某种方式通过数据进行循环。使用C ?

的Google测试是否有一些直接的方式

您可以使用GTEST的价值参数测试。

Combine(g1, g2, ..., gN)发电机一起使用它就像您最好的选择。

以下示例填充了2个 vector s,一个 int s之一,另一个string s,然后仅使用一个测试固定装置,为2 vector s中可用值组合创建测试:

#include <iostream>
#include <string>
#include <tuple>
#include <vector>
#include "gtest/gtest.h"
std::vector<int> ints;
std::vector<std::string> strings;
class CombinationsTest :
    public ::testing::TestWithParam<std::tuple<int, std::string>> {};
TEST_P(CombinationsTest, Basic) {
  std::cout << "int: "        << std::get<0>(GetParam())
            << "  string: "" << std::get<1>(GetParam())
            << ""n";
}
INSTANTIATE_TEST_CASE_P(AllCombinations,
                        CombinationsTest,
                        ::testing::Combine(::testing::ValuesIn(ints),
                                           ::testing::ValuesIn(strings)));
int main(int argc, char **argv) {
  for (int i = 0; i < 10; ++i) {
    ints.push_back(i * 100);
    strings.push_back(std::string("String ") + static_cast<char>(i + 65));
  }
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

使用一个结构数组(称为Combination)保存您的测试数据,并在单个测试中循环每个条目。使用EXPECT_EQ而不是ASSERT_EQ检查每个组合,以免测试中止,您可以继续检查其他组合。

Combination的Overload operator<<,以便您可以将其输出到ostream

ostream& operator<<(ostream& os, const Combination& combo)
{
    os << "(" << combo.field1 << ", " << combo.field2 << ")";
    return os;
}

Combination的Overload operator==,以便您可以轻松地比较两个组合的平等:

bool operator==(const Combination& c1, const Combination& c2)
{
    return (c1.field1 == c2.field1) && (c1.field2 == c2.field2);
}

和单位测试看起来像这样:

TEST(myTestCase, myTestName)
{
    int failureCount = 0;
    for (each index i in expectedComboTable)
    {
        Combination expected = expectedComboTable[i];
        Combination actual = generateCombination(i);
        EXPECT_EQ(expected, actual);
        failureCount += (expected == actual) ? 0 : 1;
    }
    ASSERT_EQ(0, failureCount) << "some combinations failed";
}