我正在尝试验证对函数的调用不会导致与mock的任何交互。但是,mock是在类的构造函数中调用函数之前使用的。
这不起作用,因为与mock:有交互
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进行其他交互,则需要更改测试,即使测试不测试构造函数。
有其他选择吗?
静态导入Mockito时,您可以重置mock:Mockito.reset(someMock);
或仅重置reset(someMock);
。
此方法采用可变数量的参数,因此您甚至可以执行reset(someMock1, someMock2, ...);