Hamcrest lessThan not compiling

Trying to compile this code

import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.lessThan; ... Assert.assertThat(0, is(lessThan(1))); 

throws this compilation error:

assertThat(Object, org.hamcrest.Matcher<java.lang.Object>) cannot be applied to (int, org.hamcrest.Matcher<capture<? super java.lang.Integer>>)

Can there be these collisions between different versions of hamcrest? I am using jUnit 4.6 and hamcrest 1.3

+6
java unit-testing junit hamcrest
source share
4 answers

I believe the problem is that JUnit comes bundled with the old version of Hamcrest (1.1), since signatures in a later version of Hamcrest are not compatible with JUnit. There are two possible solutions:

  • Drop the Hamcrest version (1.3) from the class path and use the copy bundled with JUnit.
  • Use a different version of the JUnit version (I believe the jars are called "junit-dep-xxx.jar) which do not include Hamcrest
  • Change calls to org.junit.Assert.assertThat() to org.hamcrest.MatcherAssert.assertThat () `.

The latter is probably my recommended option, as the version of Hamcrest assertThat() produces more nice error messages, and versions with later versions have some nice features (like TypeSafeDiagnosingMatcher ).

+5
source share

I do not use Hamcrest, but obviously int not an object. Use Integer instead, for example.

 Assert.assertThat(Integer.valueOf(0), is(lessThan(1))); 

I assume that you are using the Java version <= 1.4, where automatic boxing does not work. Therefore, you must first explicitly convert to Integer .

+1
source share

I think that maybe the problem is with your assertThat method. If he says

 void assertThat(Object item, Matcher<Object> matcher) { ... } 

then you need to change it to:

 void <T> assertThat(T item, Matcher<? super T> matcher) { ... } 

Perhaps your JUnit library is outdated compared to your Hamcrest library? Did you build them yourself? Perhaps you have multiple copies of JUnit or Hamcrest in your class path?

+1
source share

This is a very strange problem. I think we need more information, as it should work correctly. I tried to play it using JUnit 4.4 and Hamcrest 1.1 (a bit older, but this is what I use in the current project, so it was easy to check), and it worked fine.

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.

This may be because you are using an old version of Hamcrest or JUnit (which versions are you actually using? You haven't mentioned this yet). The strange thing is that you received an error message, even if you added an explicit cast to Integer . This is interesting, and it can be useful when posting this error ...

In any case, it should work just fine, as there are no syntax errors or anything else, so your installation should be the cause of the problem.

0
source share