我正在尝试验证是否在 DAO 内部调用了 (void) 方法 - 我正在使用一个提交点,该提交点发送到该点的结果列表,重置列表并继续。假设我在列表中有 4 件事并且我的提交点为 1,我希望“发送”方法被调用 4 次。我可以通过编写来验证该方法是否被调用一次
Mockito.verify(mock).send()
它通过了..但我想验证它被调用的次数。我会认为
Mockito.verify(mock.send(), times(4))
就足够了,但它说参数不正确,无法验证。
顺便说一句,如果我更改 Mockito.verify(mock).send()为 Mockito.verify(mock.send())或 Mockito.verify((mock).send())我得到同样的错误。对此有什么想法?
Mockito.verify(mock.send())
Mockito.verify((mock).send())
必要的方法是Mockito#verify:
public static <T> T verify(T mock, VerificationMode mode)
mock是您的模拟对象,mode是VerificationMode描述应如何验证模拟的对象。可能的模式是:
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方法和这些验证模式:
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 次,它将失败。
send
如果您只想检查该方法是否已被调用一次,则无需传递VerificationMode. 一个简单的
verify(mock).someMethod("was called once");
就足够了。它在内部使用verify(mock, times(1)).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, 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 次时,测试用例为绿色。