So stellen Sie mithilfe von Hamcrest und Mockito fest, dass die Oberklassenliste dem Unterklassen-Matcher entspricht
Frage
Ich versuche Folgendes zu tun.
final Matcher<SuperClass> matcher1 = Matchers.hasProperty("a", equalTo("b"));
final Matcher<SuperClass> matcher2 = Matchers.hasProperty("c", equalTo("d"));
final Matcher<SuperClass> matchers = Matchers.allOf(matcher1, matcher2);
List<SubClass> list = someStuff();
assertThat(list, everyItem(matchers));
Ich erhalte einen Kompilierungsfehler in der Assert-Zeile. Gibt es eine einfache Möglichkeit, diesen zu beheben?
Lösung
Option 1:
@SuppressWarnings({"unchecked", "rawtypes"})
@Test public void yourTest() {
final Matcher<SuperClass> matcher1 = Matchers.hasProperty("a", equalTo("b"));
final Matcher<SuperClass> matcher2 = Matchers.hasProperty("c", equalTo("d"));
final Matcher<SuperClass> matchers = Matchers.allOf(matcher1, matcher2);
List<SubClass> list = someStuff();
// Note cast to raw type here, corresponding to the suppressed warnings.
assertThat(list, (Matcher) everyItem(matchers));
}
Option 2:
// These are all of type Matcher<SubClass> instead.
final Matcher<SubClass> matcher1 = Matchers.hasProperty("a", equalTo("b"));
final Matcher<SubClass> matcher2 = Matchers.hasProperty("c", equalTo("d"));
final Matcher<SubClass> matchers = Matchers.allOf(matcher1, matcher2);
List<SubClass> list = someStuff();
assertThat(list, everyItem(matchers));
Warum? Javas Generika-Handhabung ist für Hamcrest zu clever. everyItem(matchers)
werde a zurückgeben Matcher<Iterable<SuperClass>>
, aber Sie haben kein Iterable<SuperClass>
, du hast ein Iterable<SubClass>
.Es wäre alles in Ordnung, wenn Ihre Matcher-Methoden tatsächlich eine erzeugen würden Matcher<Iterable<? extends SuperClass>>
, aber es ist für Sie fast unmöglich, Java davon zu überzeugen matcher1
Und matcher2
sind miteinander kompatibel.
Andere Tipps
Generics.
The problem with your code is that you try to assert that a list with type List<SubClass>
matches every item of a matcher with type Matcher<SuperClass>
.
Even though SuperClass
extends SubClass
, the assertThat
method requires the two to be the same.
So if you can coerce your someStuff()
method to return a list of of SuperClass
, you should be home free. I.e. something like this
List<SuperClass> list = someStuff();
assertThat(list, everyItem(matchers));
would get rid of the compilation error.