Hamcrest number comparison using between
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>
I don't believe between
is part of the core hamcrest matchers, but you could do something like this:
assertThat(number, allOf(greaterThan(min),lessThan(max)));
That's still a little ugly, so you could create a helper method between
assertThat(number, between(min,max))
and between
looks like
allOf(greaterThan(min),lessThan(max))
Still not a fantastic solution, but it reads like a hamcrest matcher.
If you can't find one that's publicly available, it would be trivial to write your own between
matcher http://code.google.com/p/hamcrest/wiki/Tutorial.
If you're dealing with integers, you should consider using the closeTo
method:
assertThat((double)nclient, is(closeTo(nserver, 1d)));
unfortunately, there's no closeTo
for integers, but every 32 bit integer is representable by a double, so you can simply cast them to doubles, and carry on.
This is not exactly equivalent to between
, but can sometimes be helpful.