Irbis
Irbis

Reputation: 13369

Gmock parameterized tests running twice

Here is an example code:

struct MyFixture: public ::testing::Test
{
};

template <typename param>
struct MyFixtureWithParam: public MyFixture, public ::testing::WithParamInterface<param>
{
};

using MyFixtureWithNumber = MyFixtureWithParam<int>;

TEST_P(MyFixtureWithNumber, Test1)
{
    std::cout << "Test1 with param: " << GetParam() << std::endl;
}

INSTANTIATE_TEST_CASE_P(Test1, MyFixtureWithNumber, ::testing::Values(0,3));

TEST_P(MyFixtureWithNumber, Test2)
{
    std::cout << "Test2 with param: " << GetParam() << std::endl;
}

INSTANTIATE_TEST_CASE_P(Test2, MyFixtureWithNumber, ::testing::Values(5, 7));

I expect to get 4 test (2 instances for Test1 and 2 instances for Test2), but 8 tests is run. Why? How to fix that?

Upvotes: 2

Views: 1034

Answers (1)

aschepler
aschepler

Reputation: 72271

INSTANTIATE_TEST_CASE_P(prefix, fixture, generator)

registers tests to be run for every parameterized test case which uses the same fixture type. The prefix is only used in building names for the parameterized tests, which appear in output and can be used with a --gtest-filter command-line argument.

So if you want Test1 and Test2 to run with different sets of parameter values, you'll need to force them to be different fixture types:

// ...

struct MyFixtureForTest1 : public MyFixtureWithNumber {};
struct MyFixtureForTest2 : public MyFixtureWithNumber {};

TEST_P(MyFixtureForTest1, Test1)
{
    std::cout << "Test1 with param: " << GetParam() << std::endl;
}

INSTANTIATE_TEST_CASE_P(SmallValues, MyFixtureForTest1, ::testing::Values(0,3));

TEST_P(MyFixtureForTest2, Test2)
{
    std::cout << "Test2 with param: " << GetParam() << std::endl;
}

INSTANTIATE_TEST_CASE_P(LargeValues, MyFixtureForTest2, ::testing::Values(5, 7));

Upvotes: 2

Related Questions