[英]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. 确保method
只使用某个参数object
调用一次,即没有第二个调用method(differentObject)
但是我希望有一种方法可以简化我仍然不知道的方法。 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). 如果我正确地读了你,你需要验证模拟被调用一次且只调用一次并且单个调用有一个等于object
的参数(我对上面包含的any(Object.class)
有点困惑)。 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
. 在更复杂的情况下,您可以使用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... 编辑:将Jan的评论/解决方案放在哪里更具可读性......
verify(mock, only()).someMethod();
The above verifies is exactly the same as the two calls of verify
and verifyNoMoreInteractions
above. 以上验证与上面的两个verify
和verifyNoMoreInteractions
调用verifyNoMoreInteractions
。
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. 另一种机制是使用建议的ArgumentCaptor
。
There is no way to simplify it, as far as I can tell. 据我所知,没有办法简化它。 You do need to write the two verify(mock).method(...)
calls. 你需要写两个verify(mock).method(...)
调用。 The only other ways would be to use an ArgumentCaptor
or an Answer
, but they are no simpler. 唯一的其他方法是使用ArgumentCaptor
或Answer
,但它们并不简单。
The use of only()
(as suggested in another answer) does not work, as explained and exemplified in the API documentation for this method. only()
使用only()
(如另一个答案中所建议的)不起作用,如此方法的API文档中所解释和举例说明的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.