Hamcrest to compare superclass and subclass

I have the following classes:

abstract class Answer<T> {}
class AnswerInt extends Answer<Integer> {}
class AnswerText extends Answer<String> {}

Now I would like to use the Hamcrest Matcher in the following test (this is just a simplified example):

@Test
public void test() {
    Answer a = new AnswerInt(5);
    assertThat(a, is(new AnswerInt(5))); // Compile error
}    

but I get a compile error: The method assertThat(T, Matcher<? super T>) in the type MatcherAssert is not applicable for the arguments (Answer, Matcher<AnswerInt>).

I see an error message, but I do not understand why assertThatis defined as .. Matcher<? super T>.

Is it possible to write statements that mix superclass and subclass?

Next, I would like to write statements such as:

Map<String,Answer> answerMap = questionary.getAnswerMap();
assertThat(answerMap, allOf(
    hasEntry("var1", new AnswerInt(5)),
    hasEntry("var2", new AnswerText("foo"))
));

But I get the same error.

I am using Hamcrest version 1.3

+4
source share
2 answers

If you run your test with Java 8, it compiles. For previous versions you need to give a hint:

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

equalTo (...)

assertThat(a, equalTo(new AnswerInt(5)));

, , - downcast, , :

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>) ...
0

All Articles