I’m looking for the best practice for C++ codings style that will ensure ease of unit tests. The question comes from trying to implement a mock class for a private data member. The private data member is accessed in a few different methods in the class. So far all the examples I can find show how to write a mock class but not how to best write the code that will use both real and mocked objects.
In the example below I’m not sure how to get mCustom from type MyOtherClass to my mock MockMyOtherClass. I suspect my approach is wrong and thus the question.
class MyClass {
MyOtherClass mCustom;
};
[EDIT]
I went with a compiler directive and a added a new constructor.
#ifdef UNIT_TESTING
#include "mock.h"
#else
#include "myotherclass.h"
#endif
class MyClass {
MyOtherClass mCustom;
public:
MyClass(MyOtherClass pClass) : mCustom(pClass) {}
};
There are a few different strategiers you can use (and mix as needed).
If MyOtherClass provides fairly basic functionality and is well-tested itself, then I usually don’t bother with mocking it. I just make sure that, when running unit-tests on the entire project, MyOtherClass is tested before MyClass.
You can templatize MyClass, providing MyOtherClass in the real code, and a mock version of MyOtherClass in the test code.
You can split MyOtherClass in a interface class and and an implementation class. MyClass only stores a pointer to the interface class and gets a reference to an implementation when it gets instantiated.
You can play tricks with the search-path for headers. To do this, you create a mock version of MyOtherClass in a separate directory. You then ensure that for the unit-tests, this separate directory is searched first for header files. This makes that the mock version of MyOtherClass is found first and overrides the real version of MyOtherClass.