c++googletestgooglemock

When mocking a class via MOCK_METHOD, does it need the override keyword?


Lets say I have

class Foo {
 public:
    VIRTUAL_FOR_TEST void bar(int i);
};

where it's mocked via

class FooMock : public Foo {
 public:
    MOCK_METHOD(void, bar, (int), ());
};

Foo should only be virtual for the sake of unit testing as there's no needed inheritence for it in production code. Do you still need to provide the override keyword to MOCK_METHOD?

Edit:

If override is needed, why is it optional to enter? Why isn't override default to MOCK_METHOD?


Solution

  • override is never required. It was added in C++11 to help programmers convey intention clearly and to catch silly typos by making compiler throw an error if method marked with override does not in fact override anything.

    MOCK_METHOD is a macro that expands to a regular function declaration (well, this and another function that is the mock body). Since you aren't required to add override specifier in any case, you aren't required to do so here either. And I had used MOCK_METHOD without override as a workaround for GMock limitation (it couldn't mock a function that returns a move only type back in the day).

    It is definitely a good idea to add override since it helps to catch a change in code without having to wonder "why does this mock not get called". While I somewhat agree with commenters that you should test code that you execute, I also think one should not modify code just for testing purposes. Advice to "change your design" works in Java where you have to pay the cost of virtual functions anyway, but not necessarily in C++.