验证是否使用mockito调用了三个方法之一
我有这样的三个方法:
public void method1(String str){
...
}
public void method1(String str, String str2, String str3){
...
}
public void method1(String str, String str2, Object[] objs, String str3){
...
}
我想在 Mockito 中检查是否调用了这些方法中的任何一个,因此我尝试使用 anyVararg Matcher:
verify(foo).method1(anyVararg());
但这不会编译“类型中的方法 method1(String, String)”错误不适用于参数(对象)”
我有两个问题:
- 我该如何解决这个问题?
- 有没有办法检查是否调用了两个方法中的任何一个?想象一下我有另一种方法,称为方法 2 和方法 3。我想检查是否调用了其中任何一个(但至少有一个)。
谢谢。
I have three methods like these ones:
public void method1(String str){
...
}
public void method1(String str, String str2, String str3){
...
}
public void method1(String str, String str2, Object[] objs, String str3){
...
}
I want to check in Mockito if any of these methods are invoked, so I've tried to use anyVararg Matcher:
verify(foo).method1(anyVararg());
but this doesn't compile "The method method1(String, String) in the type Errors is not applicable for the arguments (Object)"
I have two questions:
- How can I solve this?
- Is there any way to check if any of two methods are invoked? Imagine I have another mathods called method2 and method3. I'd like to check if any of them is invoked (but at least one).
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过使用
Answer
在调用任何方法时增加计数器来实现此目的。请注意,您需要存根所有方法。方法的唯一性基于其签名,而不仅仅是方法名称。两个同名的方法仍然是两个不同的方法。
请参阅
doAnswer
文档此处< /a>.You could do this by using an
Answer
to increment a counter if any of the methods are called.Note that you need to stub all methods. A method's uniqueness is based on its signature and not just the method name. Two methods with the same name are still two different methods.
See documentation for
doAnswer
here.可变参数方法具有如下签名:
没有一个方法是可变参数方法。
我不了解 Mockito,所以我无法为您解决您的问题,但是除非您使用反射,否则不可能对上述所有三种方法进行抽象,所以我想您将不得不对上述每种方法使用单独的情况方法。
A vararg method has a signature like this:
None of your methods is a vararg method.
I don't know Mockito so I can't solve your problem for you, but there is no possible abstraction over all three of the above methods unless you use reflection, so I guess you will have to use separate cases for each of the above methods.
您可以拦截对对象的所有调用,如下答案所示:
Mockito - 拦截模拟上的任何方法调用
然后将其与@Bozho建议的方法结合起来:
注意:如果您为任何此方法提供其他拦截器 - 默认将不会被调用。
You can intercept all calls on object like in this answer:
Mockito - intercept any method invocation on a mock
and then put combine this with approach suggested by @Bozho:
Note: if you provide other interceptor for any of this methods - default will not be invoked.