Call private method with PowerMock

Last Updated on by

Post summary: How to invoke private method with PowerMock.

This post is part of PowerMock series examples. Code shown in examples bellow is available in GitHub java-samples/junit repository.

Unit test private method

Mainly public methods are being tested, so it is very rare case where you want to unit test private method. PowerMock provides utilities that can invoke private methods via a reflection and get output which can be tested.

Code to be tested

Bellow is a sample code that shows a class with private method in it. It does nothing else but increasing 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 instance of the object, method name as a String and arguments to call method with. In example bellow 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));
	}
}

Conclusion

PowerMock provides utilities which uses reflection to do certain things, as show in example above to invoke private method.

If you find this post useful, please share it to reach more people. Sharing is caring!
Share on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someone
Category: Java, Unit testing | Tags: ,