Mockito: How do I verify that the array passed to my method contains the right object?

8.3k views Asked by At

I’m using Mockito 1.9.5. I want to verify that my method (which takes an array as a param) was called in which the array contains exactly one specific object. I’m having trouble figuring out how to do this. I have

Mockito.doReturn(new SaveResult[]{}).when(mockConnection).update(org.mockito.Matchers.any(SObject[].class));
…     

Mockito.verify(mockConnection, Mockito.times(1)).update( new Account[]{ acct });

Unsurprisingly, the second line fails because although the argument, “acct” is the same as what is passed, the enclosing array is not. What is the best way to check for this?

2

There are 2 answers

0
Mureinik On BEST ANSWER

Mockito has a builtin matcher, AdditionalMatchaer#aryEq(T[]) for this usecase exactly:

Mockito.verify(mockConnection, Mockito.times(1))
       .update(aryEq(new Account[]{ acct }));
2
Jeff Bowman On

In addition to Mockito's built-in aryEq() matcher, you can use argThat() with one of Hamcrest's array Matchers. The arrayContaining matcher is a good starting point.

Note that in modern versions of Mockito (newer than 2.1.0 in Sept 2016), you'll need to use MockitoHamcrest.argThat; ArgumentMatchers.argThat (exposed via static inheritance as Mockito.argThat) no longer depends on Hamcrest. This avoids a version dependency between Hamcrest and Mockito's core files.

Though MockitoHamcrest was considered for separation/deprecation/deletion in 2019 (see mockito#1817 and mockito#1819) the file still exists without visible deprecation as of v4.3.1 in January 2022. ArgumentMatchers.argThat is still preferable for lambdas and small custom implementations, but to use Hamcrest's extensive built-in matcher library you'll need MockitoHamcrest as an adapter (or you'll need to adapt it yourself via ArgumentMatchers.argThat).