This post explains how to stub private methods of a class using PowerMock. Lets consider a class named “Class1” with the structure as shown below
Classes to be tested
package package3;
public class Class1 {
private int method1(int value1) {
return value1 + 2;
}
public int method2(int value2) {
return this.method1(value2);
}
}
We want to test method2 but don’t want method1 logic to be included in the test. So we stub method1
Test Class
1 package package3;
2
3 import static org.junit.Assert.assertEquals;
4
5 import org.junit.Before;
6 import org.junit.Test;
7 import org.junit.runner.RunWith;
8 import org.powermock.api.mockito.PowerMockito;
9 import org.powermock.core.classloader.annotations.PrepareForTest;
10 import org.powermock.modules.junit4.PowerMockRunner;
11
12 @RunWith(PowerMockRunner.class)
13 @PrepareForTest(Class1.class)
14 public class Class1Test {
15
16 private Class1 class1;
17
18 @Before
19 public void setUp() {
20 class1 = new Class1();
21 class1 = PowerMockito.spy(class1);
22 }
23
24 @Test
25 public void testMethod1() throws NoSuchMethodException, Exception {
26 PowerMockito.when(class1, "method1", 5).thenReturn(5);
27 assertEquals(5, class1.method2(5));
28 }
29 }
Explanation
As shown in the above code we annotate the test class with @RunWith(PowerMockRunner.class) to indicate the JUnit to use PowerMockRunner to execute the test class. We tell the Powermock to prepare the class to be tested by adding annotation @PrepareForTest.
To stub a private method, we need to create a spy object which wraps an instance of the class which contains the method to be stubbed. In this case Class1, so we create an instance at line 20.
At line 21 we create a spy object and assigned it to variable class1.
At line 26 we mock the private method. The when method takes three arguments
1) the spy instance
2) the name of the private method
3) argument the private method receives
At line 26, we are telling PowerMockito to return 5 when the argument passed to private method is 5, using “thenReturn” method.