Junit assert OR condition in my test case

Leem.fin picture Leem.fin · Sep 25, 2013 · Viewed 38.6k times · Source

In my test case, I get an integer value:

int val = getXXX();

Then, I would like to check if val either equals to 3 or equals to 5 which is OK in either case. So, I did:

assertTrue(val == 3 || val==5);

I run my test, the log shows val is 5, but my above assertion code failed with AssertionFailedError. Seems I can not use assertTrue(...) in this way, then, how to check true for OR condition?

Answer

Joe picture Joe · Sep 28, 2013

You can use Hamcrest matchers to get a clearer error message here:

int i = 2;
assertThat(i, Matchers.either(Matchers.is(3)).or(Matchers.is(5))

or

int i = 2;
assertThat(i, Matchers.anyOf(Matchers.is(3),Matchers.is(5)));

This will more clearly explain:

Expected: (is <3> or is <5>)
     but: was <2>

showing exactly the expectation and the incorrect value that was provided.