Mockito argument matchers are powerful tools used in unit testing to flexibly specify arguments when setting up mocks. However, they come with several limitations:
1. Usage Context: Argument matchers can only be used within the context of stubbing or verifying methods. They cannot be used when calling methods on the object under test. For instance, you cannot use `anyString()` when calling a method on a real object; instead, you should use a concrete value[1][5].
2. Consistency Across Arguments: When using an argument matcher for one argument, all other arguments must also use matchers. You cannot mix matchers with concrete values for different arguments in the same method call. This is a common source of the `InvalidUseOfMatchersException`[7][8].
3. Mocking Limitations: Mockito cannot mock certain methods like `equals()`, `hashCode()`, or final methods. While argument matchers can be used with methods that can be mocked, they do not extend the capability to mock these restricted methods[3].
4. Argument Matcher Types: Mockito provides a variety of built-in argument matchers (e.g., `anyInt()`, `anyString()`, `isNull()`), but you must choose the correct type for the argument. For example, using `any()` with a primitive type might not work as expected; instead, use a more specific matcher like `anyBoolean()` for boolean parameters[7].
5. Custom Argument Matchers: While Mockito allows you to create custom matchers using the `argThat()` method, implementing the `ArgumentMatcher` interface requires careful consideration to ensure the matcher behaves as expected in different scenarios[2][4].
6. Integration with Other Libraries: When using Mockito with other libraries like Hamcrest, ensure that the integration is properly handled. For example, SonarQube might flag certain uses of `argThat()` with Hamcrest matchers as incorrect, even if they are valid[4].
In summary, while Mockito argument matchers are versatile, their usage is restricted to specific contexts and requires consistency across method arguments. Additionally, they do not overcome the fundamental limitations of Mockito regarding certain methods or classes.
Citations:[1] https://groups.google.com/g/mockito/c/Ul9yMcZqnKY
[2] https://kenkousen.substack.com/p/tales-from-the-jar-side-a-mockito
[3] https://ioflood.com/blog/mockito/
[4] https://community.sonarsource.com/t/problem-with-java-rule-s6073-mockito-argument-matchers-in-case-of-usage-mockitohamcrest-adapter/38429
[5] https://groups.google.com/g/mockito/c/Zi6PCqudTco
[6] https://www.lambdatest.com/automation-testing-advisor/selenium/methods/org.mockito.ArgumentMatchers.isNull
[7] https://stackoverflow.com/questions/16458136/mockito-invalid-use-of-argument-matchers
[8] https://www.baeldung.com/mockito-argument-matchers