Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do you combine argument matchers with specific values in Mockito


How do you combine argument matchers with specific values in Mockito


Combining argument matchers with specific values in Mockito is not directly supported. When using Mockito, you must either use argument matchers for all arguments or use specific values for all arguments. If you try to mix both, Mockito will throw an `InvalidUseOfMatchersException`.

Using Argument Matchers for All Arguments

If you want to use argument matchers, you should apply them to all arguments of the method you are stubbing or verifying. For example:

java
when(mockFoo.bool(anyString(), anyInt(), any(Object.class))).thenReturn(true);

In this case, `anyString()`, `anyInt()`, and `any(Object.class)` are used for all arguments.

Using Specific Values for All Arguments

Alternatively, you can use specific values for all arguments:

java
when(mockFoo.bool("specificString", 10, "specificObject")).thenReturn(true);

Here, `"specificString"`, `10`, and `"specificObject"` are specific values.

Using `eq()` for Specific Values

If you want to use a specific value for an argument while still using matchers for other arguments, you can use the `eq()` method provided by Mockito. This allows you to specify a specific value while still using matchers for other arguments:

java
when(mockFoo.bool(eq("specificString"), anyInt(), any(Object.class))).thenReturn(true);

In this example, `"specificString"` is a specific value wrapped in `eq()`, while `anyInt()` and `any(Object.class)` are matchers for the other arguments.

Important Considerations

- Consistency: Ensure that either all arguments use matchers or all use specific values (or `eq()` for specific values).
- `eq()` Usage: Use `eq()` to specify exact values when you need to mix specific values with matchers.
- Error Handling: Mixing matchers and raw values without `eq()` will result in an `InvalidUseOfMatchersException`.

By following these guidelines, you can effectively use argument matchers and specific values in your Mockito tests.

Citations:
[1] https://www.digitalocean.com/community/tutorials/mockito-argument-matchers-any-eq
[2] https://codingcraftsman.wordpress.com/2020/04/17/mockito-matchers-precedence/
[3] https://github.com/etorreborre/specs2/issues/854
[4] https://www.softwaretestinghelp.com/mockito-matchers/
[5] https://javadoc.io/static/org.mockito/mockito-core/2.2.7/org/mockito/ArgumentMatcher.html
[6] https://www.scalatest.org/user_guide/using_matchers
[7] https://stackoverflow.com/questions/63481301/can-i-mix-one-matcher-and-1-exact-value-in-mockito-arguments
[8] https://www.youtube.com/watch?v=_-EKS7kkeKo