Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces vs Templates for dependency injection in C++

To be able to unit test my C++ code I usually pass the constructor of the class under test one or several objects that can be either "production code" or fake/mock objects (let's call these injection objects). I have done this either by

  1. Creating an interface that both the "production code" class and the fake/mock class inherits.
  2. Making the class under test a template class that takes the types of the injection objects as template parameters, and instances of the injection objects as parameters to the constructor.

Some random thoughts:

  • Until we have concepts (C++0x), only documentation and parameter naming will hint what to provide the class under test (when using templates).
  • It is not always possible to create interfaces for legacy code
  • The interface is basically only created to be able to do dependency injection
  • In the same way: templating the class under test is done only to enable dependency injection

What are your thoughts? Are there other solutions to this problem?

like image 218
Tobias Furuholm Avatar asked Sep 06 '25 07:09

Tobias Furuholm


2 Answers

With C++, there's another option - you give your mock classes exact same names as the real classes, and when linking your unit tests, just link them with mock object/library files instead of real ones.

like image 157
Pavel Minaev Avatar answered Sep 10 '25 06:09

Pavel Minaev


I think interface option is better, but one doesn't have to create common base class just for test. You can inherit your mock class from production class and override necessary methods. You'll have to make the methods virtual though, but that's how tools like mockpp work and they also allow automate this process a little bit.

like image 30
Oleg Zhylin Avatar answered Sep 10 '25 08:09

Oleg Zhylin