Trying to compile this code
import static org.hamcrest.Matchers.is;
import static org.hamcrest.number.OrderingComparison.lessThan;
...
Assert.assertThat(0, is(lessThan(1)));
issues this compilation error:
assertThat(Object, org.hamcrest.Matcher<java.lang.开发者_StackOverflow中文版Object>)
cannot be applied to(int, org.hamcrest.Matcher<capture<? super java.lang.Integer>>)
Could be this collisions between different hamcrest versions? I'm using jUnit 4.6 and hamcrest 1.3
I believe the problem is that JUnit comes bundled with an older copy of Hamcrest (1.1) as signatures in later version of Hamcrest are incompatible with JUnit. There are two possible solutions:
- Drop your version of Hamcrest (1.3) from the classpath, and use the copy bundled with JUnit.
- Use a different release version of JUnit (I believe the jars are named like 'junit-dep-xxx.jar) which does not include Hamcrest
- Change calls of
org.junit.Assert.assertThat()
to org.hamcrest.MatcherAssert.assertThat()`.
The latter is probably my recommended option, since the Hamcrest version of assertThat()
produces nicer failure messages, and versions later than 1.1 have some nice features (e.g. TypeSafeDiagnosingMatcher
).
I don't use Hamcrest, but obviously int
isn't an Object. Use Integer
instead, e.g.
Assert.assertThat(Integer.valueOf(0), is(lessThan(1)));
I suppose you are using Java version <= 1.4 where auto-boxing doesn't work. Hence you need an explicit conversion to Integer
first.
I think perhaps the problem is your assertThat method. If it says,
void assertThat(Object item, Matcher<Object> matcher) { ... }
then you need to change it to:
void <T> assertThat(T item, Matcher<? super T> matcher) { ... }
Maybe your JUnit library is out of date compared to your Hamcrest library? Did you build them both yourself? Do you possibly have multiple copies of JUnit or Hamcrest in your classpath?
It is a very strange problem. I think we need some more information, since it should work correctly. I tried to reproduce it using JUnit 4.4 and Hamcrest 1.1 (a bit older, but that's what I'm using at my current project, so it was easy to test) and it worked perfectly.
The only difference I noticed is that my Eclipse imported org.hamcrest.Matchers.lessThan
instead of org.hamcrest.number.OrderingComparisons.lessThan
, but when I used the latter it worked flawlessly as well.
It could be caused by the fact that you using an old version of Hamcrest or JUnit (which versions are you actually using? You didn't mentioned it yet). What is strange is the fact that you got an error even when you've added an explicit cast to Integer
. That's interesting, and it could be helpful when you post this error...
Anyway, it should work perfectly since there are no syntax errors or something, so your setup has to be the cause of the problem.
精彩评论