我正在尝试验证对函数的调用不会引起与模拟的任何交互。但是,该类模拟是在类的构造函数中调用函数之前使用的。

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

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);


这很脆弱,因为如果构造函数更改为可以与模拟进行其他交互,则即使测试未测试构造函数,也需要更改测试。

还有其他选择吗?

最佳答案

您可以重置模拟:Mockito.reset(someMock);或仅当静态导入Mockito时重置reset(someMock);

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

09-26 22:50