Search code examples
c++mockinggoogletest

For gtest, how to mock methods which have the same name, but different types


I use Gtest to verify my C++ code, and now I face a mocking problem. For several reasons, I have some methods, which have the same name, but different type arguments and implementation, like

void foo(int& i);
void foo(double& d);
void foo(float& f);

For them, I make mock methods, like

MOCK_METHOD1(foo, void(int&));
MOCK_METHOD1(foo, void(double&));
MOCK_METHOD1(foo, void(float&));

However, I could not use EXPECT_CALL for them. In a test code, I set action for foo(int), like

EXPECT_CALL(mock_object, foo(_)).WillOnce(DoAll(SetArgReferee<0>(10),Return()));

but, compiler failed because target is ambiguous among int, double and float.

Is there any way to use EXPECT_CALL for specific type mock method?

I failed to use testing::MatcherCast and testing::SafeMatcherCast, because they only accept const type. However, I need to update the argument, so I could not use const.


Solution

  • You can use typed wildcard (documentation):

    EXPECT_CALL(mock_object, foo(An<int&>())).WillOnce(SetArgReferee<0>(10));
    EXPECT_CALL(mock_object, foo(A<double&>())).WillOnce(SetArgReferee<0>(10.));
    

    A<> and An<> mean exactly the same, they have two names just for nicer reading. See it online on godbolt


    Side note: You don't have to Return() from void method.