In a Java unit test, how do I assert a number is within a given range?

I will use AssertJ as Jonathan said, but with simpler assertions :)

 assertThat(mynum).isBetween(min, max);

I think this is the coolest solution :)


you can use Hamcrest library too ,this is more readable.

assertThat(mynum,greaterThanOrEqualTo(min));

assertThat(mynum,lessThanOrEqualTo(max));

Those lines can be merged via allOf like this:

assertThat(mynum, allOf(greaterThanOrEqualTo(min),lessThanOrEqualTo(max)));

Extending on this answer: you can combine the two with allOf.

assertThat(mynum, allOf(greaterThanOrEqualTo(min),lessThanOrEqualTo(max)));

The OR equivalent in Hamcrest is anyOf.


I'd write:

assertTrue("mynum is out of range: " + mynum, min <= mynum && mynum <= max);

but technically you just need:

assertTrue(min <= mynum && mynum <= max);

Either way, be sure to write && and not and.

Tags:

Java

Junit