【问题标题】:Assert that actual value is in a collection of possible expected values断言实际值在可能的期望值的集合中
【发布时间】:2021-02-17 16:03:19
【问题描述】:

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

例子:

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

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

assertThat(permittedTransformations, contains(actual));

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

【问题讨论】:

  • hamcrest 有匹配器 in()oneOf() 可以与 is() 组合,所以你可以写:is(in(permittedTransformations))
  • @SergeiTonoian 谢谢,我找不到in(),但我找到了类似名称的org.hamcrest.collection.IsIn.isIn(),这正是我想要的。我之前没有找到它,因为我只在 CoreMatchers 中查找。
  • 我可能正在检查最新版本的文档,但是是的,您也可以使用 isIn(),但不知道您使用的是什么版本,但现在它已被弃用
  • @SergeiTonoian 感谢您让我知道弃用,我确实在我们的旧代码库中使用了旧版本。

标签: java junit4 hamcrest


【解决方案1】:

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

【讨论】:

  • 谢谢。将reduceeither 结合使用是一个好主意,尽管我刚刚发现org.hamcrest.collection.IsIn.isIn() 这正是我所寻找的。但我会记住你的想法以备将来使用。
猜你喜欢
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 2021-11-28
  • 2012-09-26
  • 1970-01-01
相关资源
最近更新 更多