如何验证方法被调用两次与Mockito verify()


307

我想通过嘲笑验证来验证是否至少调用一次方法。我用了验证,它抱怨像这样:

org.mockito.exceptions.verification.TooManyActualInvocations: 
Wanted 1 time:
But was 2 times. Undesired invocation:

Answers:


519

使用适当的VerificationMode:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

22
您也可以使用Mockito.times(...)代替VerificationModeFactory.times(...)静态导入
Wim Deblauwe

26
import static org.mockito.Mockito.times;。通常不建议导入带有“内部”(import static org.mockito.internal.verification.VerificationModeFactory.times;)的软件包。
罗杰

还有另一种书写times(1)的方式吗?
Glenn Bech

1
@GlennBech 您可以忽略它,它是隐式的。默认情况下,verify(mockObject).someMethod("")查找的恰好是1个互动(不多也不少)。相反,如果您希望至少一次调用该方法,则可以使用说明atLeastOnce()符。
nbrooks

1
@Roger我同意你的观点,对于像我这样的TDD初学者来说,静态导入使我更加难以记住方法或所使用的框架(Mockito,Espresso或只是普通的单元测试)。
两次编码法一次
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.