我有以下课程:
abstract class Answer<T> {}
class AnswerInt extends Answer<Integer> {}
class AnswerText extends Answer<String> {}
现在我想在下面的测试中使用Hamcrest Matcher(它只是简单的例子):
@Test
public void test() {
Answer a = new AnswerInt(5);
assertThat(a, is(new AnswerInt(5))); // Compile error
}
但我收到编译错误:
The method assertThat(T, Matcher<? super T>) in the type MatcherAssert is not applicable for the arguments (Answer, Matcher<AnswerInt>)
。
我确实理解了错误消息,但我不明白为什么assertThat
被定义为... Matcher<? super T>
。
是否可以编写混合超类和子类的断言?
接下来,我想写一些断言,如:
Map<String,Answer> answerMap = questionary.getAnswerMap();
assertThat(answerMap, allOf(
hasEntry("var1", new AnswerInt(5)),
hasEntry("var2", new AnswerText("foo"))
));
但是我得到了同样的错误。
我使用的是Hamcrest 1.3版
答案 0 :(得分:4)
如果您使用Java 8运行测试,它将进行编译。对于以前的版本,您必须为编译器提供一个提示:
@Test
public void test() {
Answer a = new AnswerInt(5);
assertThat(a, Matchers.<Answer>is(new AnswerInt(5)));
}
答案 1 :(得分:0)
我尝试使用equalTo(...)
assertThat(a, equalTo(new AnswerInt(5)));
我们尝试做的是贬低,所以如果你这样做:
assertThat(new AnswerInt(5), is(a));
仔细查看消息:
The method assertThat(T, Matcher<? super T>) in the type Assert is not applicable for the arguments (Answer<Integer>, Matcher<AnswerInt>)
但你确实做了类似的事情:
assertThat(<? super T>, Matcher<T>) ...