Unit Testing Private Methods

Every now and then, the same question comes up in a mailing list or a discussion group. How to test a private method? Well, the short answer is you don't. As the Section 4 – Item 11 of the JUnit FAQ states: "Testing private methods may be an indication that those methods should be moved into another class to promote reusability".

If you make a search on this subject, you'll notice that the experts consider it a code-smell if you feel the need to test your private methods. But don't break your encapsulation to fit your unit tests. If you feel that your private method is complex enough to test, there's probably a class that tries to detach itself.

However, if you insist then you can use the PrivilegedAccessor class as shown in the following example: PrivilegedAccessorTest.

Comments