必要的方法是 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()
这将验证该方法是否在模拟对象上被调用了 4 次。如果调用次数少于或超过 4 次,它将失败。send
如果您只想检查,如果该方法已被调用一次,则无需传递.一个简单的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 次时,测试用例为绿色。