Unit testing with C/C++: Lessons, what to remember?

  1. Unit tests have to run automatically on every checkin (or, unit tests that are written then forgotten are not unit tests).
  2. 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.
  3. 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.. alt text


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:

  1. 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...
  2. 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).
  3. 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.