Search code examples
c++c++11googlemock

Mock Methods that are not virtual


I have a class say A like mentioned below :

class A
{
void show()
{}
int data(int x)
{}
.....
};

I need to mock the class - since the member functions are not virtual - can I design my mock class like mentioned below:

class MockA : public A
{
MOCK_METHIOD0(show, void ());
MOCK_METHIOD1(data, int (int));
}

Can I implement this way and is there a chance from MockA to miss out mocking of any function of class A? Objects created using MockA will ever anyway land up calling class A actual method implementation?


Solution

  • Generally for this case you do not have the mock inherit from A and instead use a compile time mechanism to select whether to use an implementation class or a mock class. E.g. templating everything that uses A and then instantiating the templates with either A or MockA, to replace the production class with the mock one in the testing setup. Any methods that are not implemented in the mock, but which are called, result in a compile time error. The use of the macros in the mock definition are pretty much the same even though the methods are non-virtual.

    The hard part is replacing the class everywhere. Templates, referencing the class name via a macro, or using the same class name and making sure only one is linked are all possibilities.