Unit testing with C/C++: Lessons, what to remember?
- Unit tests have to run automatically on every checkin (or, unit tests that are written then forgotten are not unit tests).
- Before fixing a bug, write a unit test to expose it (it should fail). Then fix the bug and rejoice as the test turns green.
- It's OK to sacrifice a bit of "beauty" of a class for easier testing (like provide public methods that should not really be public, but help your testing/mocking).
Read this... you will anyway..
I'm against all of these recommendations for automatically granting friendship to test classes...
Personally I prefer to focus on the following to allow me access to the insides of a class that I need to test:
- Rely on the public interface of the class where possible; sometimes this means extending the public interface slightly to allow for easier testing. Don't fight these extensions too much but also don't let them drive your design too much...
- Consider adding a monitoring interface which can be used by 'real' code as well as test code to enable monitoring of the code under test. (I still surprise myself with how often this is a really good part of the design process).
- Consider providing access to some parts of the class to derived classes via a 'protected interface' and derive a 'testable' version of the class in question that can then be instrumented and tested.
In summary, I much prefer to see designed in test points rather than a blanket friendship with a test class. Of course the former is harder to do than the latter but, IMHO, results in better code AND better tests.