Verify object attribute value with mockito
Solution 1:
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());
Solution 2:
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
.