Dependency injection and mocking classes using C++ and google-mock library

Arco

Currently I am building tests for an existing implementation of IDM. I am using google-mock, a mocking library for C++ classes. Let’s see an example of dependency injection. This basic technique is used when you are mocking your classes and, thus, obtain non-fragile tests.

Suppose the following class hierarchy and the ‘‘Trainer’‘ class:

class Animal {
public:
  virtual int walk(int steps) = 0;
};
 
class Kangaroo: public Animal {
public:
  int walk(int steps) { return 2*steps; }
};
 
class Trainer {
public:
  int orderWalk(Animal* animal) { cout << animal->walk(4) << endl; }
};
 
int main() {
  Trainer trainer;
  trainer.orderWalk(new Kangaroo());
  return 0;
}

A Trainer needs an Animal at the orderWalk() member. In the sample code, a Kangaroo is passed to such method, but we can modify this issue. Suppose we want to ensure that the orderWalk() method calls to walk(). Let’s do it with mocks:

#include <gmock/gmock.h>
 
using namespace ::testing::Return;
 
[... rest of the code ...]
 
class AnimalMock: public Animal {
  MOCK_METHOD1(walk, int(int steps))
      .Times(1)
      .WillOnce(Return(5*steps));
};
 
int main() {
  Trainer trainer;
  AnimalMock mock;
 
  EXPECT_CALL(mock, walk(4))
      .Times(1);
 
  trainer.orderWalk(&mock);
 
  return 0;
}

First, AnimalMock is implemented by the google-mock library using the MOCK_METHOD1 directive. This implementation lets you set expectations about the mock. This is done in the main() function. An expectation is configured before calling to orderWalk, and it is as follows: we expect the walk() method to be executed with 4 as parameter just 1 time over mock object.

And that’s is. You can get more information about mocks at google-mock documentation.

Comentarios

Opciones de visualización de comentarios

Seleccione la forma que prefiera para mostrar los comentarios y haga clic en «Guardar las opciones» para activar los cambios.
Imagen de shakaran

-

Interesante el artículo, no conocía google-mock, aunque más que el blog de cleto, es una wiki no? Smiling

Today is a good day. Would you be tomorrow?