What is the correct way to use Mockito’s generic any()
method instead of anyObject()
?
I have an interface with a method that expects an array of Foo
:
public interface IBar {
void doStuff(Foo[] arr);
}
I am mocking this interface using Mockito, and I want to verify that doStuff()
is called, but I don’t care what arguments are passed.
How can I rewrite the following code using any()
, the generic method, instead of anyObject()
?
IBar bar = mock(IBar.class);
...
verify(bar).doStuff((Foo[]) anyObject());
Use any(Foo[].class) (Preferred Method)
IBar bar = mock(IBar.class);
...
verify(bar).doStuff(any(Foo[].class));
This is the most type-safe and recommended approach. It uses any()
with the correct class type (Foo[].class)
to specify that the method doStuff()
can accept any array of Foo objects.
Use ArgumentMatchers.any() (Alternative)
:
import static org.mockito.ArgumentMatchers.any;
IBar bar = mock(IBar.class);
...
verify(bar).doStuff(any(Foo[].class));
Explanation: This is essentially the same as the first solution but uses the ArgumentMatchers.any() from the Mockito library’s static import. This method is also generic, and it works in the same way as any(Foo[].class)
, providing a clean and readable solution.
Use ArgumentCaptor for Array Arguments
ArgumentCaptor<Foo[]> captor = ArgumentCaptor.forClass(Foo[].class);
IBar bar = mock(IBar.class);
…
verify(bar).doStuff(captor.capture());
Foo[] capturedArray = captor.getValue();
// Now you can assert or inspect the captured array
Instead of using any(), you can use ArgumentCaptor to capture the argument passed to the doStuff() method. This is useful when you want to inspect or verify the actual contents of the array.
While this solution requires capturing the argument, it can be helpful for more detailed assertions.