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?
example
Mockito.verify(mockedObject) .someMethodOnMockedObject( Mockito.<SomeObjectAsArgument>anyObject())
Instead of doing anyObject()
i want to check that argument object contains some particular fields
Mockito.verify(mockedObject) .someMethodOnMockedObject( Mockito.<SomeObjectAsArgument>**compareWithThisObject()**)
Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.
Mockito requires that we provide all arguments either by matchers or exact values. There are two more points to note when we use matchers: We can't use them as a return value; we require an exact value when stubbing calls. We can't use argument matchers outside of verification or stubbing.
Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments. Instead use the isNull matcher.
The argThat argument matcher in Mockito lets you create advanced argument matchers that run a function on passed arguments, and checks if the function returns true . If you have a complicated class that can't be easily checked using . equals() , a custom matcher can be a useful tool.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With