2

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?

tjwrona1992
  • 8,614
  • 8
  • 35
  • 98
  • You need a [typed wildcard](https://github.com/google/googletest/blob/release-1.8.0/googlemock/docs/CheatSheet.md#wildcard) - `PrintValue(An)` or `PrintValue(A)`. Pretty sure there was a duplicate somewhere, let me look for it. – Yksisarvinen Jun 17 '21 at 15:04
  • See [selecting-between-overloaded-functions-selectoverload](https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#selecting-between-overloaded-functions-selectoverload) – Jarod42 Jun 17 '21 at 15:07
  • Related to [why-does-google-mocks-find-this-function-call-ambiguous](https://stackoverflow.com/questions/14844720/why-does-google-mocks-find-this-function-call-ambiguous) – Jarod42 Jun 17 '21 at 15:11
  • Thanks @Yksisarvinen, using `PrintValue(A())` worked! – tjwrona1992 Jun 17 '21 at 15:15

1 Answers1

5

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;).

Dharman
  • 30,962
  • 25
  • 85
  • 135
Schallbert
  • 66
  • 1
  • 3