Reputation: 2830
I need two checks
verify(mock).method(any(Object.class));
verify(mock).method(object); // instance of Object...
to ensure the method
is called exactly once with the certain parameter object
, i.e. there is no second call method(differentObject)
however I hope there is a way to simplify that I still don't know. Is this to uncommon?
Upvotes: 3
Views: 159
Reputation: 32949
verify(mock).method(object);
verifyNoMoreInteractions(mock);
If I read you correctly you need to verify that the mock was called once and only once and that the single call had an argument equal to object
(I am a little confused by your inclusion of any(Object.class)
above). If so, this is very common and the above solution works well.
Another way you can do this in a more complicated situation is to use an ArgumentCaptor
. This will grab all invocations and allow you to verify that the correct number of invocations were made and get each argument passed in order.
EDIT: To place Jan's comment / solution where is is more readable...
verify(mock, only()).someMethod();
The above verifies is exactly the same as the two calls of verify
and verifyNoMoreInteractions
above.
In order to verify that only one call was made to a method (with argument matching) and not do any verification of other method calls, try...
verify(mock).method(object); // verify that there was one call matching
// the expected argument
verify(mock).method(any(Object.class)); // verify that there only one and only one call
The other mechanism is to use the ArgumentCaptor
suggested.
Upvotes: 3
Reputation: 16380
There is no way to simplify it, as far as I can tell. You do need to write the two verify(mock).method(...)
calls. The only other ways would be to use an ArgumentCaptor
or an Answer
, but they are no simpler.
The use of only()
(as suggested in another answer) does not work, as explained and exemplified in the API documentation for this method.
Upvotes: 1