I need a mock implementation of a class - for testing purposes - and I'm wondering how I should best go about doing that. I can think of two general ways:
I'm used to doing it the first way in Java, and it's quite common too (probably since they have a dedicated interface type). But I've hardly ever seen such interface-heavy designs in C++, thus I'm wondering.
The second way will probably work, but I can't help but think of it as kind of ugly. Is anybody doing that?
If I follow the first way, I need some naming assistance. I have an audio system that is responsible for loading sound files and playing the loaded tracks. I'm using OpenAL for that, thus I've called the interface "Audio" and the implementation "OpenALAudio". However, this implies that all OpenAL-specific code has to go into that class, which feels kind of limiting. An alternative would be to leave the class' name "Audio" and find a different one for the interface, e.g. "AudioInterface" or "IAudio". Which would you suggest, and why?
Just as I would not hand-author mock objects in Java, I would also not hand-author them in C++. Mock objects are not just stubbed out classes, but are test tools that perform automated checks like making sure certain methods are called, or that they are called in order, etc. I would take a look at the various mock object frameworks for C++ out there. googlemock looks interesting, but there are others.
Regarding how to abstract out the concept of controlling Audio resources from the implementation, I definitely favor using a C++ "interface" (pure virtual base class) with a generic name (e.g. Audio
) and an implementation class named for what makes it special (e.g. OpenALAudio
). I suggest you not embed the word "interface" or "I" into your class names. Embedding type or programmatic concepts into names has been falling out of vogue for many years (and can force widespread renaming when you, for example, elevate an "interface" to a full-fledged "class").
Developing to interfaces is an object-oriented concept and thus appropriate for C++. Some of the most important books on design specifically targeting C++ are all about programming to interfaces (which in C++ terms means programming using pure virtual base classes). For example, Design Patterns and Large Scale C++ Software Design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With