Hamcrest number comparison using between

saw303 picture saw303 · Oct 8, 2012 · Viewed 23.1k times · Source

Is there a way in Hamcrest to compare a number within a number range? I am looking for something like this:

assertThat(50L, is(between(12L, 1658L)));

Answer

Christoph Leiter picture Christoph Leiter · Oct 8, 2012

An alternative to Jeff's solution is to use both:

assertThat(50L, is(both(greaterThan(12L)).and(lessThan(1658L))));

I think that's quite readable. You also get a good error message in case the check failed:

Expected: is (a value greater than <50L> and a value less than <1658L>) got: <50L>