A few correct results using Hamcrest (is there an or-matcher?)

I belong to newcomers with co-authors. I play with hamcrest in conjunction with JUnit and I like it.

Is there a way to indicate that the correct choice is one of several options?

Something like

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

The method I'm testing returns a single item in the collection. The list may contain several candidates. My current implementation returns the first hit, but this is not a requirement. I would like my test file to be successful if any of the possible candidates is returned. How do you put it in Java?

(I am open to hamcrest alternatives)

+60
java junit hamcrest matcher
30 sept '08 at 11:55
source share
2 answers
 assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3))) 

From the Hamcrest Tutorial :

anyOf - matches if matches, short circuits match (for example, Java ||)

See also Javadoc .

Alternatively, you can write your own Matcher, which is pretty easy to do.

+89
Sep 30 '08 at 14:13
source share

Marcos is right, but you have a couple of other options. First of all, there is either / or:

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

but if you have more than two elements, this is likely to become cumbersome. Plus, typechecker is sometimes weird in such things. For your case, you can do:

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

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

 assertThat(result, isIn(theCollection)) 

See also Javadoc .

+70
Jul 02 '11 at 2:20
source share



All Articles