Search code examples
javaunit-testingjunitmockitopowermockito

PowerMockito is calling real method instead of mocked private one


I have a class that have a private method and calls another private method in its body. So I want to invoke first private method and to mock second one. Here is an example:

public class ClassWithPrivateMethod {

    private int count;

    public ClassWithPrivateMethod() {
    }

    private void countDown() {
        while (isDecrementable())
            count--;
    }

    private boolean isDecrementable() {

        throw new IllegalArgumentException();
//        if (count > 0) return true;
//        return false;
    }
}

And test class:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithPrivateMethodTest.class)
public class ClassWithPrivateMethodTest {

    private int count;
    private ClassWithPrivateMethod classWithPrivateMethod;

    @Before
    public void setUp() throws Exception {
        count = 3;
        classWithPrivateMethod = PowerMockito.spy(new ClassWithPrivateMethod());
    }

    @Test
    public void countDown() throws Exception {

        Whitebox.setInternalState(classWithPrivateMethod, "count", count);
        PowerMockito.doReturn(true, true, false).when(classWithPrivateMethod, "isDecrementable");

        Whitebox.invokeMethod(classWithPrivateMethod, "countDown");

        int count = Whitebox.getInternalState(classWithPrivateMethod, "count");

        assertEquals(1, count);

        PowerMockito.verifyPrivate(classWithPrivateMethod, times(3)).invoke("isDecrementable");
    }
}

I invoked first private method by Whitebox.invokeMethod(classWithPrivateMethod, "countDown"); and mock second one like this, PowerMockito.doReturn(true, true, false).when(classWithPrivateMethod, "isDecrementable");. As you see isDecrementable method should return true, true, false values when called, but PowerMockito is calling real method.

I am using these dependencies:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.5</version>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.19</version>
</dependency>

What is wrong with my test?


Solution

  • I found mistake in this line:

    @PrepareForTest(ClassWithPrivateMethodTest.class)
    

    It should be:

    @PrepareForTest(ClassWithPrivateMethod.class)