Unit testing with -fno-access-control

I would argue that unit tests should not need access to private members.

In general, unit tests are meant to test the interface to your classes, not the internal implementation. That way, changes to the internals will only break the tests if the interface has been compromised.

Have a look at my answer to a similar question, and the ensuing discussion. It is a controversial topic, to be sure, but that's my $0.02.


I normally try to use only the public interface of my classes in unit tests. Test Driven Development/Design helps a lot here as the resulting classes tend to enable this style of unit test.

However sometimes you do need to let a unit test access non public members, eg replace the contents of a Singleton with a Fake instance. For this I use package protection in Java and friends in C++.

Some people seem to bend over backwards to avoid friends but they should be used when appropriate and their use doesn't compromise the design. They are also declarative and let other programmers know what you are doing.