Search code examples
c++googletestgooglemock

How to run the same google test case with different google mocks?


There are several test cases which was using a service. The test cases are written with google test. The service can be of different types, so I have mocked each one with google mock. How do I write the tests in such a way so they can be run with different mocks without writing the same tests again and again with different mocks?

The same test case for 2 different mocks are written like this:

// For mock A
TEST_F(MockASampleTest, sample_test_case)
{
    EXPECT_CALL(mockA, mockAFunc(_))
        .Times(1)
        .WillOnce(Return(mockARetVal));
    EXPECT_EQ(testObj.testFunc(), 32);
}

// For mock B
TEST_F(MockBSampleTest, sample_test_case)
{
    EXPECT_CALL(mockB, mockBFunc(_))
        .Times(1)
        .WillOnce(Return(mockBRetVal));
    EXPECT_EQ(testObj.testFunc(), 32);
}

So, the problem is that the EXPECT_CALLS are different for different mocks due to different method names and return values of the mocks. How can I combine these 2 test cases into one?


Solution

  • If you use GoogleMock framework to create and control mocks during the tests' execution, you can specify (using e.g. EXPECT_CALLS) how the mock should behave.

    The object under tests shouldn't care about what type of mock is used in given tests if you use Dependency Inversion Principle from SOLID (i.e. there should be no code that depend on mock type in the class under test; the tested class should depend on interface, not concrete implementation)