Java Mockito anyMapOf 嵌套泛型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21783219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mockito anyMapOf nested generics
提问by Ben Pennell
I am attempting to verify that a method with the following signature was called:
我正在尝试验证是否调用了具有以下签名的方法:
public void process(Map<String, Set<String>> data) {
...
}
The nested parameterized Set is causing me difficulties. I can get it to verify correctly with the any() matcher like so:
嵌套的参数化 Set 给我带来了困难。我可以让它使用 any() 匹配器正确验证,如下所示:
verify(dataProcessor).process(Matchers.<Map<String, Set<String>>> any());
As described in Mockito: Verifying with generic parametersalthough annoyingly it doesn't work if I do a direct static import of Matchers.any and call it as just:
如Mockito: Verifying with generic parameters 中所述,虽然烦人的是,如果我直接静态导入 Matchers.any 并将其称为:
verify(dataProcessor).process(<Map<String, Set<String>>> any())
But anyMapOf(clazz, clazz) seems the more appropriate matcher in this case. Since you can't do Set.class I'm not sure how you would do this. The following doesn't work because of the lack of generic:
但是 anyMapOf(clazz, clazz) 在这种情况下似乎是更合适的匹配器。因为你不能做 Set.class 我不知道你会怎么做。由于缺乏泛型,以下不起作用:
verify(dataProcessor).process(anyMapOf(String.class, Set.class));
Is it possible to verify this situation with anyMapOf or should I stick with Matchers.<>any()?
是否可以使用 anyMapOf 来验证这种情况,还是应该坚持使用 Matchers.<>any()?
采纳答案by Jeff Bowman
There's no way to use anyMapOf
to do this. It's designed to help with the simple case of mapping simple classes to simple classes in Java 7, and yours is more complex than that.
没有办法anyMapOf
用来做到这一点。它旨在帮助解决将简单类映射到Java 7 中的简单类的简单情况,而您的情况比这更复杂。
Java 8 parameter inference improved, so in Java 8, you can just use any()
.
Java 8 参数推理得到改进,因此在 Java 8 中,您只需使用any()
.
verify(dataProcessor).process(Matchers.any());
Barring that, the best way to make this look is either like you wrote above:
除此之外,使这种外观看起来像你上面写的最好的方法是:
verify(dataProcessor).process(Matchers.<Map<String, Set<String>>>any());
Or by extracting the matcher to a static function, which gives Java just enough information it needs to infer the type on its own:
或者通过将匹配器提取到一个静态函数,它为 Java 提供了它自己推断类型所需的足够信息:
@Test public void yourTest() {
// ...
verify(dataProcessor).process(anyStringSetMap());
}
private static Map<String, Set<String>> anyStringSetMap() {
return any();
}
(Caveat: Note that the return value of anyStringMap
is null; it's the side-effect of calling any
that you're looking for. The extracted method is just to inform the Java compiler of the expected return type; beware that doing anything fancier will probably break in really-quite-interesting ways.)
(注意:请注意, 的返回值为anyStringMap
空;这是您正在寻找的调用的副作用any
。提取的方法只是为了通知 Java 编译器预期的返回类型;请注意,做任何更高级的操作都可能会中断以非常有趣的方式。)