Dependency injection and mocking classes using C++ and google-mock library
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:
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:
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.