简体   繁体   中英

How can I simplify verification that a method is called with certain parameters and no others?

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 , ie 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?

 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM