Mockito
Unit Testing
Java
Array Primitives
Code Implementation

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:

java
1import static org.mockito.Mockito.*;
2import static org.mockito.ArgumentMatchers.argThat;
3import java.util.Arrays;
4
5public class SomeTestClass {
6    public void testMethod() {
7        MyClass my = mock(MyClass.class);
8        my.doSomething(new int[] {1, 2, 3});
9
10        verify(my).doSomething(argThat(arr -> Arrays.equals(arr, new int[] {1, 2, 3})));
11    }
12}

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:

java
1import static org.mockito.Mockito.*;
2import static org.mockito.ArgumentMatchers.any;
3
4public class TestClass {
5    public void testMethod() {
6        MyClass my = mock(MyClass.class);
7        my.doSomething(new int[5]);
8
9        verify(my).doSomething(any(int[].class)); // Matches any int array
10    }
11}
ActionMethod to Use
Verify a method call with specific array contentargThat(arr -> Arrays.equals(arr, expectedArray))
Verify a method call with any array of a specific typeany(Type[].class)

Define these matchers carefully: a matcher that is looser than intended lets tests pass silently when they should fail.


Course
Intermediate
27 lessons
15 hours
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 course
Data 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.

Practice algorithms