Search code examples
c++googletest

Can you pass in complex types into Parameterised Tests with Google Test?


When passing values into a Parameterised Test using Google Test:

INSTANTIATE_TEST_SUITE_P(InstantiationName,
                         FooTest,
                         testing::Values("meeny", "miny", "moe"));

is there anyway to construct more c, such as a vector, before passing them into testing::Values?


Solution

  • You can pass many different types to the parametrized types, e.g. vector:

    struct VectorTest : public testing::TestWithParam<std::vector<int>> {};
    
    TEST_P(VectorTest, MyTestCase) {
        auto expectedVector = std::vector<int>{42, 314, 271, 161};
        ASSERT_EQ(expectedVector, GetParam());
    }
    
    INSTANTIATE_TEST_CASE_P(VectorInstantiationName,
                             VectorTest,
                             testing::Values(std::vector<int>{42, 314, 271, 161}));
    

    or user-defined types:

    struct MyParam {
        int i;
        std::string s;
    };
    
    struct MyTest : public testing::TestWithParam<MyParam> {};
    
    TEST_P(MyTest, MyTestCase) {
        ASSERT_EQ(42, GetParam().i);
        ASSERT_EQ("foo", GetParam().s);
    }
    
    INSTANTIATE_TEST_CASE_P(InstantiationName,
                             MyTest,
                             testing::Values(MyParam{42, "foo"}));
    

    (using INSTANTIATE_TEST_CASE_P as I'm on 1.8 currently; INSTANTIATE_TEST_SUITE_P shall be used for newer versions of gtest).