Mockito argument matchers for arrays of primitives (int[], byte[])
Codemia Knowledge Hub ·
To match a primitive array argument in Mockito, use any(int[].class) when any array of that type is acceptable, and argThat(arr -> Arrays.equals(arr, expected)) when you need to check the contents. Arrays need this extra care because their equals method compares references, not contents.
What argument matchers are for
Matchers let you match the arguments passed to a mocked method by a condition instead of an exact value. That is useful when you care about general characteristics, such as an array's length or whether it contains a certain value, rather than the exact argument.
Why primitive arrays are tricky
Arrays of primitives such as int[], double[] and byte[] are objects in Java, but comparing them with equals checks only whether two references point to the same array. Two arrays with identical contents are not "equal" in that sense, so matching them needs a content comparison.
There are two cases to handle: verifying that a method received an array with specific contents, and allowing any array of a given type.
Verifying specific array contents
Use argThat() from org.mockito.ArgumentMatchers with a lambda that compares contents using Arrays.equals:
Matching any array of a type
When the contents do not matter for the test, match any array of the right type with any() and the array class:
| Action | Method to Use |
| Verify a method call with specific array content | argThat(arr -> Arrays.equals(arr, expectedArray)) |
| Verify a method call with any array of a specific type | any(Type[].class) |
Define these matchers carefully: a matcher that is looser than intended lets tests pass silently when they should fail.
Related reading
- Modeling a graph in Python
- Mongodb - Can I use one arbiter for many replica sets?
- MongoDB - No server chosen with java async driver and replica set
- MongoDB - Query on the last element of an array?
- Mockito Mock private field initialization
- Mockito Stubbing Methods That Return Type With Bounded Wild-Cards
- Mockito PowerMock LinkageError while mocking system class
- Mockito test a void method throws an exception
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.