Skip to content

Assert that actual value is in a collection of possible expected values

Is there a way to assert that an actual value equals any of a number of values?


String original = "...";
Collection<String> permittedTransformations = Set.of("...[1]", "...[2]", "...[3]");
String actual = transform(original);
assertThat(actual, isContainedIn(permittedTransformations));

I can see that I can just swap the arguments around:

assertThat(permittedTransformations, contains(actual));

but that reverses the semantics. I’m not checking if permittedTransformations is correct; I’m checking actual.


You can map the set elements to individual Matcher<String> objects, and combine them with either:

import static;
import static org.hamcrest.CoreMatchers.either;
import static;

Collection<String> permittedTransformations = Set.of("...[1]", "...[2]", "...[3]");
Optional<Matcher<String>> matcher =
                                        .map(s -> is(s))
                                        .collect(reducing((m1, m2) -> either(m1).or(m2)));
assertThat(actual, matcher.get());