Search code examples
c++unit-testingmockinggoogletestgooglemock

How to mock const& methods with gmock


If I have:

class Foo
{
public:
virtual int Duplicate(int) const& = 0;
};

How can I define a mock object with gMock inheriting from Foo and mocking the Duplicate method?

I have tried:

class MockFoo : public Foo
{
public:
    MOCK_METHOD(int, Duplicate, (int), (const&, override));
};

but it doesn't work, do you have any suggestions?


Solution

  • At least from v1.12.x, from gmock_cook_book, use ref(&), so

    class MockFoo : public Foo
    {
    public:
        MOCK_METHOD(int, Duplicate, (int), (const, ref(&), override));
    };
    

    Demo

    For v1.10.0, there is still a workaround with indirection:

    class MockFoo : public Foo
    {
    public:
        MOCK_METHOD(int, DuplicateRef, (int), (const));
        int Duplicate(int n) const& override { return DuplicateRef(n); }
    };
    

    Demo