How to Test private Methods with JUnit

How to test private and protected methods with JUnit

Overview

JUnit is commonly used for Java unit tests. Test code is usually written for public methods, but tests for private and protected methods are often neglected.

Because white-box testing can be considered a programmer’s responsibility, every part of the code should be testable. This page explains how to test every method.

Test Source Code

First, create a simple class to test. The sample has a public addition method, a protected subtraction method, and a private multiplication method.

Testing public Methods

A normal test case can directly create an instance and call the public method. This is the ordinary JUnit testing style.

Testing protected and private Methods

Because protected and private methods cannot be called directly from an instance in the same way, use Java reflection.

Sample sample = new Sample();
Method method = Sample.class.getDeclaredMethod("{methodName}", {arg1}, {arg2}...);
method.setAccessible(true);
int actual = ({return type}) method.invoke(<instance>, {arg1}, {arg2}...);

Use the class variable available on every class and call getDeclaredMethod() to obtain the method under test. Set setAccessible(true) on the returned method so it can be accessed externally, then execute it with method.invoke().

Conclusion

Using reflection makes it possible to test methods that cannot be called directly. Bugs are a programmer’s enemy, so remove as many possible bugs as practical.