Search code examples
c++overridingvirtualgoogletest

Make sure that mocked GTest method overrides virtual method


I would like to make sure that a mocked method overrides base class virtual method. Is it possible to use MOCK_METHOD in the way when it generates method marked as override?


Solution

  • You can do that by specifying the specs parameter to the MOCK_METHOD like so,

    MOCK_METHOD(void, foo, (), (override));
    

    Quoting https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#creating-mock-classes

    The first 3 parameters are simply the method declaration, split into 3 parts. The 4th parameter accepts a closed list of qualifiers, which affect the generated method:

    • const - Makes the mocked method a const method. Required if overriding a const method.
    • override - Marks the method with override. Recommended if overriding a virtual method.

    Here is a demo on godbolt.