Hi Hamcrest.
I've been using Hamcrest for a long time (currently using 1.3.RC2) and in every
single one of my tests, it's great. But MatcherAssert.assertThat keeps giving
out compilation errors from time to time due to the way that the generic
parameter is defined in that method. This causes me headache and I needed to
find workarounds and therefore makes my code unclean.
Here is the signature of MatcherAssert.assertThat in 1.1:
public static <T> void assertThat(T actual, Matcher<T> matcher)
Here is the improved signature of MatcherAssert.assertThat since 1.2:
public static <T> void assertThat(T actual, Matcher<? super T> matcher)
The improvement made in 1.2 makes it more flexible, but it still won't solve
the following problem (you get compilation error):
CharSequence actual = "hello";
String expected = "hello";
assertThat(actual, is(expected));
That failed because "expected" (String) is a subtype of "actual"
(CharSequence), which makes the generic requirement on the matcher parameter
(which is <? super T>) to fail.
So here I'm suggesting a solution, change the generics definition of
Matcher.assertThat to something like:
public static <T, A extends T, E extends T> void assertThat2(A actual, Matcher<E> expected)
Using this with the previous example, you get T = CharSequence, A =
CharSequence, E = String, and since both CharSequence and String are subtypes
of CharSequence, your program will compile fine (just like the old
assertEquals).
Thanks.
Original issue reported on code.google.com by llaec...@gmail.com on 11 Feb 2012 at 12:55
Original issue reported on code.google.com by
llaec...@gmail.com
on 11 Feb 2012 at 12:55