Is there a way to assert that an actual value equals any of a number of values?
Example:
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.
Advertisement
Answer
You can map the set elements to individual Matcher<String> objects, and combine them with either:
import static java.util.stream.Collectors.reducing;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.is;
Collection<String> permittedTransformations = Set.of("...[1]", "...[2]", "...[3]");
Optional<Matcher<String>> matcher = permittedTransformations.stream()
.map(s -> is(s))
.collect(reducing((m1, m2) -> either(m1).or(m2)));
assertThat(actual, matcher.get());