Search code examples
mockitopowermockpowermockito

PowerMock not verifying private calls more than once


Class to be tested
    public class ClassUnderTest {
    public void functionA() {
        functionB();
        functionC();
    }
    private void functionB() {
    }
    private void functionC() {
    }
}

Test Class

@RunWith(PowerMockRunner.class)
public class TestClass {
        @Test
        public void testFunctionA() throws Exception {
            ClassUnderTest classUnderTest = PowerMockito.spy(new ClassUnderTest());
            classUnderTest.functionA();
            PowerMockito.verifyPrivate(classUnderTest).invoke("functionB");
            PowerMockito.verifyPrivate(classUnderTest).invoke("functionC");
        }
    }

While executing the test class I'm getting the following error,

org.mockito.exceptions.misusing.UnfinishedVerificationException: 
Missing method call for verify(mock) here:
-> at org.powermock.api.mockito.PowerMockito.verifyPrivate(PowerMockito.java:312)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.

If one verification is commented then the test case works fine.


Solution

  • You have to add ClassUnderTest in PrepareForTest.

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(ClassUnderTest.class)
    public class TestClass {
    
    @Test
    public void testFunctionA() throws Exception {
        ClassUnderTest classUnderTest = PowerMockito.spy(new ClassUnderTest());
        classUnderTest.functionA();
    
       PowerMockito.verifyPrivate(classUnderTest).invoke("functionB");
       PowerMockito.verifyPrivate(classUnderTest).invoke("functionC");
     }
    

    I have just added sysouts in private methods & run the test class.