在验证时,Powermock的计数超过实际调用次数

时间:2015-10-10 08:11:40

标签: java junit mockito powermock

这是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

1 个答案:

答案 0 :(得分:0)

在您的示例中,您不需要使用PowerMock,因为您没有嘲笑/监视最终或静态方法。您可以安全地删除@RunWith和@PrepareForTest注释。您的目的只需要mockito