Java – Verify object attribute value with mockito


I have a method call which I want to mock with mockito. To start with I have created and injected an instance of an object on which the method will be called. My aim is to verify one of the object in method call.

Is there a way that mockito allows you to assert or verify the object and it's attributes when the mock method is called?



Instead of doing anyObject() i want to check that argument object contains some particular fields


Best Solution

New feature added to Mockito makes this even easier,

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
assertEquals("John", argument.getValue().getName());

Take a look at Mockito documentation

In case when there are more than one parameters, and capturing of only single param is desired, use other ArgumentMatchers to wrap the rest of the arguments:

verify(mock).doSomething(eq(someValue), eq(someOtherValue), argument.capture());
assertEquals("John", argument.getValue().getName());