Mockito.any() 通过泛型接口
是否可以通过泛型传递接口的类型?
界面:
public interface AsyncCallback<T>
在我的测试方法中:
Mockito.any(AsyncCallback.class)
将
放在 or for .class
后面不起作用。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我必须采用以下机制来允许泛型:
希望这对某人有帮助。
I had to adopt the following mechamism to allow for generics:
Hope this helps someone.
将 pierrefevrier 评论发布为答案,如果它出现在答案而不是评论中,这可能会很有用。
使用新版本的 Mockito:
(Matchers.>any()
Posting pierrefevrier comment as answer which might be useful if it present in a answer instead of comments.
With new versions of Mockito:
(Matchers.<AsyncCallback<ResponseX>>any()
我在使用 Spring
Example
时遇到了类似的问题:在这里,您必须使用限定条件,b/c findAll 方法可以采用多种类型,例如
Sort
和Iterable.当然,您也可以使用带有类型安全警告的
Mockito.any(Example.class)
。I had a similar problem using Spring
Example
:Here, you have to use qualification, b/c findAll method can take multiple types, like
Sort
andIterable
. You can also useMockito.any(Example.class)
of course with the type safety warning.除了 thSoft 的回答之外,将限定调用放入方法中意味着我可以删除限定,因为返回类型允许推断:
Further to thSoft's answer putting the qualified call to any() in method meant I could remove the qualification since the return type allowed inference:
将合格的泛型类型与无参
any()
方法结合使用(即ArgumentMatchers.>any()
),但可能会变得笨拙对于更长的泛型表达式。另一种方法是将无参any()
调用放入其自己的泛型方法中,并使用特定的泛型类型作为返回类型:
Using a qualified generics type with the no-argument
any()
method works (i.e.ArgumentMatchers.<AsyncCallback<ResponseX>>any()
), but can get unwieldy for longer generics expressions. An alternative is to put a no-argumentany()
call in its own generic method, using the specific generic type as the return type:Usage
你可以直接转换它,如果你愿意的话添加抑制警告:
如果Java允许“通用”泛型,他们可能有一个像这样的方法,这就是你正在寻找的
You can just cast it, adding suppress warnings if you like:
If Java allowed 'generic' generics they could have a method like this which is what you are looking for
有一种类型安全的方法:使用
ArgumentMatchers.any()
并用类型限定它:There is a type-safe way: use
ArgumentMatchers.any()
and qualify it with the type:使用 Java 8,由于增强的类型推断,您可以简单地使用
any()
(假设静态导入)而无需参数或类型参数。编译器现在从目标类型(方法参数的类型)知道您实际上指的是Matchers.>any()
,这是 Java 8 之前的解决方案。Using Java 8, you can simply use
any()
(assuming static import) without argument or type parameter because of enhanced type inference. The compiler now knows from the target type (the type of the method argument) that you actually meanMatchers.<AsyncCallback<ResponseX>>any()
, which is the pre-Java 8 solution.