我如何验证,从某个点开始,没有更多与模拟的交互?

时间:2014-10-03 14:29:34

标签: java unit-testing testing mocking mockito

我试图验证对函数的调用不会导致与模拟的任何交互。但是,在调用函数之前,在类'中使用了 。构造

这不起作用,因为 与模拟交互:

SomeMock someMock = mock(SomeMock.class);
Subject subject = new Subject(someMock); // interactions with someMock happen here

subject.doNothingWithMock();

verifyNoMoreInteractions(someMock);

这是一个脆弱的解决方案:

SomeMock someMock = mock(SomeMock.class);
Subject subject = new Subject(someMock); // interactions with someMock happen here

verify(someMock).anInteraction();
verify(someMock).anotherInteraction();

subject.doNothingWithMock();

verifyNoMoreInteractions(someMock);

它很脆弱,因为如果构造函数更改为与mock有其他交互,则需要更改测试,即使测试没有测试构造函数。

有替代方案吗?

1 个答案:

答案 0 :(得分:2)

当静态导​​入Mockito时,您可以重置mock:Mockito.reset(someMock);reset(someMock);

此方法采用可变数量的参数,因此您甚至可以执行reset(someMock1, someMock2, ...);