1

I'm just learning to use Google Mock. It works fine when I test a class to which I can pass the mocked object as a pointer or reference (dependency injection). When I have a class which doesn't use DI, I haven't found a solution.

We currently have a lot of code which doesn't use DI and interfaces, for example:

#include "ReadDbObjects.h"

class ObjectManager
{
public:
  ObjectManager()
  {
    ReadDbObjects db_reader;
    mObjects = db_reader.ReadAll();
  }
private:
  vector<MyObject> mObjects;
}

(this is extremly simplified, but should explain the problem)

We currently test something like this by creating just for the unit test a file called ReadDbObjects.cpp (which includes the original ReadObjects.h with the class declaration), which is statically linked to the unit test. In this file, we mock the ReadAll-Method, so it returns the objects we need for the test. This file is hard to maintain and it needs another file which is known both in the ReadObjects.cpp and the unit test, so values between the test and the mocked ReadObjects-class can be passed in both directions.

  1. Is there a way to mock ReadObjects using gmock in this example?
  2. Can gmock be used, when I need to mock a base class? Here we use the same mechanism by linking a mocked cpp base class file into the unit test.
273K
  • 29,503
  • 10
  • 41
  • 64
Luc Hamers
  • 167
  • 1
  • 10
  • 1
    So gmock shows you all of your design flaws clearly (at least `factory` should be passed to the class from outside, otherwise I don't see the point of using one); at least that benefit is brought to you. – πάντα ῥεῖ Oct 24 '13 at 10:29
  • We don't use interfaces for most of the classes, since we are developing on an embedded system where ram and flash is always an issue. As far as I know, interfaces will increase at least the binary size of the program. Or am I wrong about that? Btw: I changed the name of the object from factory to db_reader, factory might be a bit confusing. – Luc Hamers Oct 24 '13 at 10:45
  • 1
    You may use [static interfaces](http://stackoverflow.com/questions/4557141/static-polymorphism-definition-and-implementation) on embedded systems. This way mocking becomes pretty easy, since you only need to change template parameters for testing. – πάντα ῥεῖ Oct 24 '13 at 11:25
  • If I understand the problem correctly, then you have a somewhat similar problem to what I had with injecting a fake query class. What I ended up doing - all of the logic that actually happened was done in a private implementation of that class whereas SQLQuery(an analogue of yours ReadDbObjects) was just a wrapper for it. Which Impl class to use at a given time could be controlled by a static variable. – Zeks Jun 19 '15 at 14:06

0 Answers0