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

3

87

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)

Stockdale answered 30/9, 2008 at 11:55 Comment(0)
U
138
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.

Unwholesome answered 30/9, 2008 at 14:13 Comment(2)
Looks like oneOf is the most recent.Ethnology
Thanks, @Richard. Indeed, oneOf sounds like a good option for this case too: hamcrest.org/JavaHamcrest/javadoc/2.2/org/hamcrest/collection/…Unwholesome
O
88

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.

Osmanli answered 2/7, 2011 at 2:20 Comment(3)
Hmmm... for some inexplicable reason my Eclipse environment (which is only about 6 months old) has an ancient Hamcrest library and I don't get these goodies.Hydrazine
Well, assertThat((Set<String>)null, is(either(empty()).or(nullValue()))); gives me a rather strange assertion error: Expected: is (an empty collection or null) but: was null for hamcrest 1.3...Euton
isOneOf() seems to be deprecated now.Exeat
K
0

In addition to the anyOf, you could also go for the either option, but it has a slightly different syntax:

assertThat(result, either(is(1)).or(is(2)).or(is(3))))
Knott answered 12/12, 2022 at 8:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.