I have a class that defines an overloaded method that I need to mock. The issue is, the two overloads both take only one argument and GMock seems to think the call is ambiguous.
Here is a small example demonstrating the problem (oversimplified for the sake of demonstration):
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <iostream>
#include <string>
using ::testing::_;
class MyClass
{
public:
virtual ~MyClass() = default;
virtual void PrintValue(const std::string& value) const
{
std::cout << value << std::endl;
}
virtual void PrintValue(const int& value) const
{
std::cout << value << std::endl;
}
};
class MyClassMock : public MyClass
{
public:
MOCK_CONST_METHOD1(PrintValue, void(const std::string&));
MOCK_CONST_METHOD1(PrintValue, void(const int&));
};
TEST(MyTest, MyTest)
{
MyClassMock mock;
EXPECT_CALL(mock, PrintValue(_)).Times(1);
mock.PrintValue(42);
}
int main(int argc, char* argv[])
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
On the EXPECT_CALL
line I get a compilation error:
error: call of overloaded 'gmock_PrintValue(const testing::internal::AnythingMatcher&)' is ambiguous
EXPECT_CALL(mock, PrintValue(_)).Times(1);
How can I get GMock to differentiate between the two overloads correctly so the call is no longer ambiguous?
I had the same issue and solved it using gMock Cookbook's Select Overload section. You have to define the matcher's type, e.g. by writing Matcher<std::string>()
. Remember to include this directive above (using ::testing::Matcher;
).