Verify object attribute value with mockito Verify object attribute value with mockito java java

Verify object attribute value with mockito


New feature added to Mockito makes this even easier,

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);verify(mock).doSomething(argument.capture());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());


I think the easiest way for verifying an argument object is to use the refEq method:

Mockito.verify(mockedObject).someMethodOnMockedObject(ArgumentMatchers.refEq(objectToCompareWith));

It can be used even if the object doesn't implement equals(), because reflection is used. If you don't want to compare some fields, just add their names as arguments for refEq.


One more possibility, if you don't want to use ArgumentCaptor (for example, because you're also using stubbing), is to use Hamcrest Matchers in combination with Mockito.

import org.mockito.Mockitoimport org.hamcrest.Matchers...Mockito.verify(mockedObject).someMethodOnMockedObject(MockitoHamcrest.argThat(    Matchers.<SomeObjectAsArgument>hasProperty("propertyName", desiredValue)));