Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 849
Mo. Avatar asked Sep 30 '08 11:09

Mo.


People also ask

Is Hamcrest a matcher?

Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.

What is the Hamcrest matcher to test if a string contains another string?

Class StringContains. Tests if the argument is a string that contains a substring. Creates a matcher that matches if the examined String contains the specified String anywhere.

Which Hamcrest matcher is just like the && operator?

Which Hamcrest matcher is just like the && operator? Explanation: Checks to see if all contained matchers match (just like the && operator). 7.


1 Answers

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.

like image 193
marcospereira Avatar answered Nov 08 '22 07:11

marcospereira