Search code examples
c++qtgoogletestgooglemock

Passing an array to parameterized test in gtest


A parameterized test in gtest allows you to test your code with different parameters without writing multiple copies of the same test.seen here

I have seen examples of passing values, std::pair, std::tuple etc.

But I'm not sure how to pass an array/initializer_list into the test.

Expected something like this :

INSTANTIATE_TEST_SUITE_P(Sample, FooTest,
                         testing::Values({1,23,53},{534,34,456));

Is it possible? If yes how?


Solution

  • You can pass any type you want as the parameter. You provide type of parameters when you inherit your test fixture a from class template WithParamInterface (or TestWithParam):

    class FooTest: public TestWithParam<std::array<int, 3>>
    //class FooTest: public TestWithParam<std::vector<int>>
    //class FooTest: public TestWithParam<std::initializer_list<int>> //I'm not sure if this is a good idea, initializer_list has weird lifetime management
    {};
    
    INSTANTIATE_TEST_SUITE_P(Sample, FooTest,
                             testing::Values(std::array<int, 3>{1,23,53},
                                             std::array<int, 3>{534,34,456});
    

    See it online.
    You cannot use bare brace-init list and let the compiler deduce type, because ::testing::Values() accepts template parameters and compiler doesn't know what type should that template argument become.

    Let's say we have class BarTest: public TestWithParam<std::string>. To ::testing::Values we can pass either actual std::string objects ::testing::Values(std::string{"asdf"}, "qwer"s) or objects implicitly convertible to std::string, like string literal: ::testing::Values("zxcv"). The latter will deduce type as const char* and the actual std::string is constructed deeper in GoogleTest code.