如何避免Mockito和PowerMockito之间的冲突?

时间:2014-08-15 15:44:32

标签: java unit-testing testng mockito powermock

我需要测试一些非常简单的类。第一个是Child类:

public class Child extends Parent {

    public int newMethod() {
        anotherMethod();
        protectedMethod();
        return protectedMethodWithIntAsResult();
    }

    public void anotherMethod() {
        // method body no so important
    }
}

比我有一个Parent班:

public class Parent {
    protected void protectedMethod() {
        throw new RuntimeException("This method shouldn't be executed in child class!");
    }

    protected int protectedMethodWithIntAsResult() {
        throw new RuntimeException("This method shouldn't be executed in child class!");
    }
}

最后我的测试类采用单一测试方法:

@PrepareForTest({Child.class, Parent.class})
public class ChildTest extends PowerMockTestCase {

    @Test
    public void test() throws Exception {

        /** Given **/
        Child childSpy = PowerMockito.spy(new Child());
        PowerMockito.doNothing().when(childSpy, "protectedMethod");
        PowerMockito.doReturn(100500).when(childSpy, "protectedMethodWithIntAsResult");

        /** When **/
        int retrieved = childSpy.newMethod();

        /** Than **/
        Assert.assertTrue(retrieved == 100500);
        Mockito.verify(childSpy, times(1)).protectedMethod();
        Mockito.verify(childSpy, times(1)).protectedMethodWithIntAsResult();
        Mockito.verify(childSpy, times(1)).anotherMethod(); // but method was invoked 3 times.
    }
}

我上次验证时遇到问题。程序引发异常:

org.mockito.exceptions.verification.TooManyActualInvocations: 
child.anotherMethod();
Wanted 1 time:
-> at my.project.ChildTest.test(ChildTest.java:30)
But was 3 times. Undesired invocation:

我不明白为什么。任何想法为什么会发生?

1 个答案:

答案 0 :(得分:-1)

当您致电int retrieved = childSpy.newMethod()时,问题就出现了,因为在那里您正在呼叫anotherMethod()protectedMethod()

Mockito假设您只会调用每个方法,但newMethod内部调用protectedMethodanotherMethodanotherMethod已被调用一次。

如果您取消对newMethodanotherMethod的调用,则测试运行正常。