In Mockito, both `never()` and `times(0)` are used to verify that a method on a mock object was not called. However, they are essentially the same in functionality, with `never()` being an alias for `times(0)`.
Functionality
- Purpose: Both methods ensure that a specific method on a mock object has not been invoked during the execution of the test. This is crucial for ensuring that certain interactions do not occur, which might be undesirable in certain scenarios.
- Usage: You can use either `never()` or `times(0)` interchangeably in the `verify` method. For example:
java
verify(mockObject, never()).someMethod();
is equivalent to:
java
verify(mockObject, times(0)).someMethod();
Readability and Cognitive Load
- Readability: Some developers might find `never()` more readable because it explicitly states the intention of verifying that a method was never called. However, both methods are widely recognized and understood in the context of Mockito.
- Cognitive Load: The existence of both methods can slightly increase cognitive load, as developers need to remember that they are equivalent. However, this is a minor concern, and most developers quickly become accustomed to using either or both methods based on personal preference.
Best Practices
- Choosing Between `never()` and `times(0)`: The choice between using `never()` or `times(0)` often comes down to personal preference or coding style guidelines within a project. Both are valid and serve the same purpose.
- Alternative Approaches: For verifying that no interactions occurred on a mock object at all, you might also consider using `verifyNoMoreInteractions(mockObject)` or `verifyNoInteractions(mockObject)`, depending on your specific testing needs.
In summary, while `never()` and `times(0)` are functionally identical, `never()` might be preferred for its explicitness in stating that a method should not have been called, whereas `times(0)` is more consistent with other Mockito verification methods like `times(1)`, `times(2)`, etc.
Citations:[1] https://www.javaguides.net/2023/10/mockito-never.html
[2] https://www.javaguides.net/2023/10/mockito-times.html
[3] https://stackoverflow.com/questions/13678976/junit-testing-difference-between-never-and-times0
[4] https://stackoverflow.com/questions/12862659/how-to-verify-that-a-specific-method-was-not-called-using-mockito
[5] https://www.lambdatest.com/automation-testing-advisor/selenium/methods/org.mockito.Mockito.times
[6] https://www.javacodegeeks.com/2015/11/mockito-verification.html
[7] https://site.mockito.org/javadoc/current/org/mockito/Mockito.html
[8] https://stackoverflow.com/questions/33671798/mockito-verify-a-function-is-invoked-0-times
[9] https://mockk.io
[10] https://www.dhiwise.com/post/mastering-unit-testing-a-complete-guide-to-mockito-verify
[11] https://softwareengineering.stackexchange.com/questions/188299/is-this-an-appropriate-use-of-mockitos-reset-method