Call private method with PowerMock
This post is part of PowerMock series examples. The code shown in examples below is available in GitHub java-samples/junit repository.
Unit test private method
Mainly public methods are being tested, so it is a very rare case where you want to unit test a private method. PowerMock provides utilities that can invoke private methods via a reflection and get output which can be tested.Code to be tested
Below is a sample code that shows a class with a private method in it. It does nothing else but increases the X and Y coordinates of given as argument Point.public class PowerMockDemo {
private Point privateMethod(Point point) {
return new Point(point.getX() + 1, point.getY() + 1);
}
}
Unit test
Assume that this private method has to be unit tested for some reason. In order to do so, you have to use PowerMock's Whitebox.invokeMethod(). You give an instance of the object, method name as a String and arguments to call the method with. In the example below argument is new Point(11, 11).import org.junit.Before;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class PowerMockDemoTest {
private PowerMockDemo powerMockDemo;
@Before
public void setUp() {
powerMockDemo = new PowerMockDemo();
}
@Test
public void testCallPrivateMethod() throws Exception {
Point actual = Whitebox.invokeMethod(powerMockDemo,
"privateMethod", new Point(11, 11));
assertThat(actual.getX(), is(12));
assertThat(actual.getY(), is(12));
}
}