必要的方法是Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
是您的模拟对象,它mode
是VerificationMode
描述如何验证模拟的对象。可能的模式是:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
您需要从Mockito
类中进行以下静态导入,才能使用verify
方法和以下验证模式:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
因此,在您的情况下,正确的语法将是:
Mockito.verify(mock, times(4)).send()
这验证了该方法在模拟对象上send
被调用了4次。如果调用次数少于或超过4次,它将失败。
如果您只想检查方法是否被调用过一次,则无需传递VerificationMode
。一个简单的
verify(mock).someMethod("was called once");
足够了。它在内部使用verify(mock, times(1)).someMethod("was called once");
。
可以在同一模拟上进行多个验证调用,以实现“之间”验证。Mockito不支持这样的东西verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
,但是我们可以写
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
相反,获得相同的行为。包括边界,因此当方法被调用4次,5次或6次时,测试用例为绿色。
Mockito.verify(mock, times(4)).send()
。我想知道为什么您“移动”了send()
方法内部的verify
方法调用。您已经有了正确的语法。