Michal Kordas
Michal Kordas

Reputation: 10925

Hamcrest assertion on two values

I can easily do an assertion with two possible results:

assertThat(result, anyOf(true, false)); // just a sample, doesn't make sense as an assertion

However, I need to perform assertion that one of my results is equal to some value:

assertThat(result1 || result2, is(true));

The above works, but error message doesn't say which result was false. Is there anything similar to the below in Hamcrest?

assertThat(anyOf(result1, result2), is(true)); // just a hypothetical assertion

Upvotes: 1

Views: 1245

Answers (1)

Tunaki
Tunaki

Reputation: 137064

You could write the assertion in reverse:

assertThat(true, anyOf(is(result1), is(result2)))

This will still throw an assertion error when either result1 or result2 isn't true, and the message will tell both final values or result1 and result2... in the expected part, which makes it a bit awkward.


From your question:

However, I need to perform assertion that one of my results is equal to some value:

This means that your real use-case is determining whether the list of your results has a given value. This can be clearly expressed with:

assertThat(Arrays.asList(result1, result2), hasItem(true));

This is asserting that the list formed by the two results has the given item. If it doesn't, the assertion error will be:

Expected: a collection containing <true>
     but: was <false>, was <false>

The message tells you the value of each element in the collection.

Upvotes: 4

Related Questions