In Mockito, `times(n)` and `atLeast(n)` are used within the `verify` method to check how many times a method is called on a mock object. Here's a detailed explanation of each:
times(n)
- Purpose: This method verifies that a method is called exactly `n` times. If the method is called more or less than `n` times, the test will fail.- Example: `verify(mock, times(2)).someMethod();` ensures that `someMethod()` is called exactly twice.
- Use Case: Use when you need to ensure a precise number of invocations.
atLeast(n)
- Purpose: This method verifies that a method is called at least `n` times. If the method is called less than `n` times, the test will fail, but it will pass if it is called more than `n` times.- Example: `verify(mock, atLeast(2)).someMethod();` ensures that `someMethod()` is called at least twice.
- Use Case: Use when you want to ensure a minimum number of invocations but do not care about the maximum.
Key Differences
- Exact vs. Minimum: `times(n)` requires an exact number of calls, while `atLeast(n)` requires at least that number of calls.- Flexibility: `atLeast(n)` is more flexible as it allows for more calls than specified, whereas `times(n)` is strict about the number of calls.
- Error Handling: If a method is called more times than specified with `times(n)`, Mockito will throw an exception (`TooManyActualInvocations`). With `atLeast(n)`, it will only fail if the method is called fewer times than specified (`TooLittleActualInvocations`).
In summary, `times(n)` is used for precise control over the number of method calls, while `atLeast(n)` is used to ensure a minimum threshold of calls without restricting the maximum number of calls.
Citations:[1] https://stackoverflow.com/questions/58176580/what-is-the-difference-between-atleastonce-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-of-verify-method-with-and-without-times1-parameter
[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-verify-a-method-which-was-called-multiple-times/54233921