使用 junit 测试地图时使用通用有界通配符
Using generic bounded wildcards when testing Maps with junit
我试图理解为什么这个 junit 断言给我一个编译时错误:
Map<String, Set<String>> actual = methodToTest();
assertThat(result, hasEntry("foo", new HashSet<String>(Arrays.asList("bar"))));
如果我这样写它就可以正常工作:
Map<String, Set<String>> actual = methodToTest();
Set<String> expected = new HashSet<String>(Arrays.asList("bar"));
assertThat(result, hasEntry("foo", expected));
第一个示例的编译器错误是:
The method assertThat(T, Matcher<? super T>) in the type Assert is not
applicable for the arguments (Map<String,Set<String>>, Matcher<Map<?
extends String,? extends HashSet<String>>>)
HashSet<String>
是 Set<String>
的子类型,为什么它不起作用?
HashSet<String>
是 Set<String>
的子类型 true.
但是,Matcher<Map<String,HashSet<String>>>
不是 Matcher<Map<String,Set<String>>>
的子集。请记住 List<String>
不是 List<Object>
.
的子类型
assertThat
方法需要一个 Matcher<? super Map<String, Set<String>>>
类型的参数,它与 Matcher<Map<String,HashSet<String>>>
.
不兼容
我试图理解为什么这个 junit 断言给我一个编译时错误:
Map<String, Set<String>> actual = methodToTest();
assertThat(result, hasEntry("foo", new HashSet<String>(Arrays.asList("bar"))));
如果我这样写它就可以正常工作:
Map<String, Set<String>> actual = methodToTest();
Set<String> expected = new HashSet<String>(Arrays.asList("bar"));
assertThat(result, hasEntry("foo", expected));
第一个示例的编译器错误是:
The method assertThat(T, Matcher<? super T>) in the type Assert is not
applicable for the arguments (Map<String,Set<String>>, Matcher<Map<?
extends String,? extends HashSet<String>>>)
HashSet<String>
是 Set<String>
的子类型,为什么它不起作用?
HashSet<String>
是 Set<String>
的子类型 true.
但是,Matcher<Map<String,HashSet<String>>>
不是 Matcher<Map<String,Set<String>>>
的子集。请记住 List<String>
不是 List<Object>
.
assertThat
方法需要一个 Matcher<? super Map<String, Set<String>>>
类型的参数,它与 Matcher<Map<String,HashSet<String>>>
.