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

后端 未结 2 738
Happy的楠姐
Happy的楠姐 2021-02-20 03:20

I have a unit test that I need to run for 200 possible combinations of data. (The production implementation has the data to be tested in configuration files. I know how to mock

2条回答
  •  面向向阳花
    2021-02-20 04:10

    Use an array of structs (called, say, Combination) to hold your test data, and loop though each entry in a single test. Check each combination using EXPECT_EQ instead of ASSERT_EQ so that the test isn't aborted and you can continue checking other combinations.

    Overload operator<< for a Combination so that you can output it to an ostream:

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

    Overload operator== for a Combination so that you can easily compare two combinations for equality:

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

    And the unit test could look something like this:

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

提交回复
热议问题