Search code examples
javaunit-testingmockito

Use of verify() method with and without times(1) parameter


I couldn't find any practical difference between these two usages. Just to avoid future complications, could it possibly cause an issue selecting randomly any one of them?

  1. verify(mockObj).foo();

  2. verify(mockObj, times(1)).foo();

If they are exactly the same, which one can be assumed as the best practice?


Solution

  • They are equivalent. From the Javadoc of Mockito#verify(T):

    Verifies certain behavior happened once.

    Alias to verify(mock, times(1)) E.g:

    verify(mock).someMethod("some arg");
    

    Above is equivalent to:

    verify(mock, times(1)).someMethod("some arg");
    

    [...]

    Which is considered better than the other is subjective. The first option (no times(1)) is shorter but the second option (with times(1)) makes the code's intentions explicit. The second option also allows you to specify a description for if and when the verification fails.

    Use whichever you and your team believe will be the most readable. In particular, make sure you'll understand the code when coming back to it at some point in the future.