Question

In our project we are using Google Mock, but in multiple places we are making contructions in our production code, only to make sure classes are "mockable". We do this because we want to have the benefits of Google Mock, but on the other side we would rather have more optimal production code. The following case is something we do often, and would like to get rid off.

class A{
  public:
    void doSomething(); //Does something with _someB
    void setSomeB(B* mockedB); //This is only here for GMock
  private:
    B* _someB; //This should not be a pointer, it is a pointer only for GMock
}

This is only a simplified example as you can see, I left out the details. Basically we want to get rid of B being a pointer. The reason we have it as a pointer, is that we can subclass B in our test code (mock it) and set it with that setter.

Is there any way to avoid this? Can't we let B be scoped in the class?

Thanks

Was it helpful?

Solution

If you really don't want _someB held as a pointer, an option would be to wrap its declaration in preprocessor commands:

#ifdef MOCK_TEST
    B _someB;
#else
    MockB _someB;
#endif

If you don't, there's no easy way to place gmock expectations and/or assertions on _someB, since it will not be an instance of a mock object. Apart from the ugliness of this, it also has the disadvantage of requiring the lib in which Class A resides to be compiled twice, once with MOCK_TEST defined and once without. It does however do away with the need for a setter for _someB.

Even if you choose to keep _someB as a pointer, perhaps a better option than creating a public setter is to declare the test class a friend class of A's to allow the test to directly set and access _someB.


As an aside, it's often considered poor form to name variables with a leading underscore.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top