断言实际值在可能预期值的集合中

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

有没有办法断言实际值等于多个值中的任何一个?

示例:

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

我可以看到我可以交换参数:

assertThat(permittedTransformations, contains(actual));

但这颠倒了语义。我不检查 permittedTransformations 是否正确;我正在检查 actual

您可以将集合元素映射到单个 Matcher<String> 对象,并将它们与 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());