Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Mockito的验证方法中的时间(n)和至少(n)之间有什么区别


Mockito的验证方法中的时间(n)和至少(n)之间有什么区别


在Mockito中,``times(n)'和`至少(n)
verify''方法中使用了``验证方法''的方法,以检查模拟对象上调用方法的次数。这是对每个的详细说明:

### Times(n)
 - 目的:此方法验证一种方法被完全称为“ n”时间。如果该方法被称为或多或少地比“ N”时间,则测试将失败。
 - 示例:`验证(模拟,时间(2))。somemethod();`确保`someMethod()`被称为两次。
 - 用例:当您需要确保精确数量的调音时使用。

###至少(n)
 - 目的:此方法验证一种方法至少称为“ n”时间。如果该方法的称为小于n`次时,则测试将失败,但是如果被称为n n time的时间多。
 - 示例:`验证(模拟,至少(2))。somemethod();`确保`至少称为两次。
 - 用例:当您想确保最少数量的调用量时使用,但不关心最大值。

###密钥差异
 - 确切与最小值:`times(n)`需要确切的呼叫数量,而``至少(n)`至少需要该数量的呼叫。
 - 灵活性:`至少(n)`更灵活,因为它允许的呼叫比指定的更多,而``times(n)
'''对呼叫的数量严格。
- 错误处理:如果一种方法比``times(n)''指定的次数多,则Mockito会抛出异常(``tomanyactualInvocations'')。使用“至少(n)”,只有在该方法被称为少于指定的次数('toolittleactualInvocations”)时才失败。

总而言之,``times(n)`用于精确控制方法呼叫的数量,而`至少(n)`用于确保呼叫的最小阈值而不限制最大呼叫数量。

引用:
[1] https://stackoverflow.com/questions/58176580/what-is-the-difference-betnewnew-ateastonce-and-times-and-times1-in-mockito
[2] https://mincong.io/2019/09/22/mockito-verify/
[3] https://github.com/mockk/mockk
[4] https://site.mockito.org/javadoc/current/org/mockito/mockito.html
[5] https://www.lambdatest.com/automation-testing-advisor/selenium/methods/org.mockito.mockito.atleast
[6] https://stackoverflow.com/questions/60969650/use-ouse-of-verify-method-with-with-and-without-times1-参数
[7] https://www.digitalocean.com/community/tutorials/mockito-verify
[8] https://stackoverflow.com/questions/27787487/java-verify-void-method-calls-n-times-with-mockito
[9] https://www.javacodegeeks.com/2015/11/mockito-verification.html
[10] https://stackoverflow.com/questions/54233024/how-to-to-verify-a-method-whoich-was-was-call-called-multiple-times/54233921