Multiple correct results with Hamcrest (is there an or-matcher?)

JavaJunitHamcrestMatcher

Java Problem Overview


I am relatively new to matchers. I am toying around with hamcrest in combination with JUnit and I kinda like it.

Is there a way, to state that one of multiple choices is correct?

Something like

assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest

The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java?

(I am open to hamcrest-alternatives)

Java Solutions


Solution 1 - Java

assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3)))

From Hamcrest tutorial:

> anyOf - matches if any matchers match, short circuits (like Java ||)

See also Javadoc.

Moreover, you could write your own Matcher, which is quite easy to do.

Solution 2 - Java

marcos is right, but you have a couple other options as well. First of all, there is an either/or:

assertThat(result, either(is(1)).or(is(2)));

but if you have more than two items it would probably get unwieldy. Plus, the typechecker gets weird on stuff like that sometimes. For your case, you could do:

assertThat(result, isOneOf(1, 2, 3))

or if you already have your options in an array/Collection:

assertThat(result, isIn(theCollection))

See also Javadoc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMo.View Question on Stackoverflow
Solution 1 - JavamarcospereiraView Answer on Stackoverflow
Solution 2 - JavaTylerView Answer on Stackoverflow