Unit testing of private methods [duplicate]

I am in the process of writing some unit tests. In particular I want to test some private methods.

So far the I have come up with using.

#define private public

But I am not happy with this as it will destroy all encapsulation from the point of view of the unit test.

What methods do you use to unit-test private methods.


Rather than the nasty #define hack you mention in the question, a cleaner mechanism is to make the test a friend of the class under test. This allows the test code (and just the test code) access to the privates, whilst protecting them from everything else.

However, it is preferable to test through the public interface. If your class X has a lot of code in the private member functions then it might be worth extracting a new class Y which is used by the implementation of class X. This new class Y can then be tested through its public interface, without exposing its use to the clients of class X.


If you're using Google Test, you can use FRIEND_TEST to easily declare your test fixture as a friend to the class under test.

And you know, if testing private functions were unequivocally bad like some of the other answers were saying, then it probably wouldn't be built into Google Test.

You can read more about when testing private functions is good or bad in this answer.


If the methods are complex enough to warrant testing in isolation, then refactor them into their own class(es) and test via their public interface(s). Then use them privately in the original class.