Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest's lessThan doesn't compile

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

like image 979
ripper234 Avatar asked Nov 30 '09 17:11

ripper234


People also ask

Is assertThat actual is Equalto expected ))) a valid Hamcrest assert statement?

assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.

Why are there Hamcrest matchers?

Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.

Is Hamcrest a matcher?

Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.


2 Answers

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:

  1. Drop your version of Hamcrest (1.3) from the classpath, and use the copy bundled with JUnit.
  2. Use a different release version of JUnit (I believe the jars are named like 'junit-dep-xxx.jar) which does not include Hamcrest
  3. 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).

like image 157
Grundlefleck Avatar answered Oct 04 '22 11:10

Grundlefleck


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.

like image 41
sfussenegger Avatar answered Oct 04 '22 09:10

sfussenegger