Mock private method using PowerMockito

You just need to change the mock method call to use doReturn.

Example Partial Mocking of Private Method

Test code

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClient.class)
public class MyClientTest {

    @Test(expected = RuntimeException.class)
    public void testPublicAPI() throws Exception {
        MyClient classUnderTest = PowerMockito.spy(new MyClient());

        // Change to this  

        PowerMockito.doReturn(20).when(classUnderTest, "privateApi", anyString(), anyInt());

        classUnderTest.publicApi();
    }
}

Console trace

In publicApi
result : 20

Leave a Comment