我有以下 class :

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版

最佳答案

如果您使用Java 8运行测试,则会进行编译。对于以前的版本,您必须给编译器一个提示:

@Test
public void test() {
    Answer a = new AnswerInt(5);
    assertThat(a, Matchers.<Answer>is(new AnswerInt(5)));
}

08-26 07:26