Search code examples
c++googlemock

GMOCK - mock an object and its inside mock method


I am writing a GMOCK test cases for a class:

class A{ .. void Text() .. };

Now one of the member method of class A has an class B type object embedded into it and also refers to static member methods:

void A::Text()
{
B bobj;
B::SMethod();
bobj->BMethod();
......
}

In such a case how can I mock B and its methods?


Solution

  • Instead of testing A, you can test a class derived from it, let's call it TestableA. In A make Text() virtual and in override use mock of the B. Also, have a look at this question for more ideas of how to mock classes with static methods.

    Nevertheless, the best solution would be to break existing tight dependency between A and B by introducing an interface (e.g. InterfaceB) and injecting it into Text(). SMethod() would become a (non-static) member of the interface. In production you'd be injecting ActualB where ActualB::SMethod() calls static B::SMethod(). In tests you'd use MockB::SMethod(), tailored by test needs.