验证时 Powermock 的计数比实际调用的多

Powermock counts more than actually call when verify

是 Powermock 的错误还是我做错了什么?

以下测试应该通过,但失败了:

trackBugPartialMockCountMore(com.xiaomi.finddevice.test.testcase.PowerMockBug)
org.mockito.exceptions.verification.TooManyActualInvocations: 
classToMock.foo();
Wanted 1 time:
-> at com.xiaomi.finddevice.test.testcase.PowerMockBug.trackBugPartialMockCountMore(PowerMockBug.java:24)
But was 3 times. Undesired invocation:
-> at com.xiaomi.finddevice.test.testcase.PowerMockBug.trackBugPartialMockCountMore(PowerMockBug.java:22)

当我删除@PrepareForTest(ClassToMock.class) 时,一切顺利,测试通过。

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassToMock.class)
public class PowerMockBug {

    @Test
    public void trackBugPartialMockCountMore() {
        ClassToMock mock = mock(ClassToMock.class);
        when(mock.foo()).thenCallRealMethod();

        mock.foo();

        verify(mock).foo();
    }

}


class ClassToMock {
    public int foo() { return 0x10; }
}

版本:powermock-mockito-junit-1.6.3

在您的示例中,您不需要使用 PowerMock,因为您不是 mocking/spying final 或静态方法。您可以安全地删除 @RunWith 和 @PrepareForTest 注释。您的目的只需要 mockito