我有一个对象列表,我想对对象本身进行真理式断言,但我没有看到任何合理的方式表达比平等断言更复杂的东西。我想象的是:
assertThat(list).containsElementThat().matches("Foo .* Bar");
假设在真理中没有这个,那么表达这样的东西最真实的方式是什么?如果我知道列表中的哪个位置,我可以说:
assertThat(list).hasSize(Math.max(list.size(), i));
assertThat(list.get(i)).matches("Foo .* Bar");
但是(除了有点hacky)只有在事先知道i
并且不适用于任意迭代的情况下才有效。有没有比自己做的更好的解决方案?
答案 0 :(得分:3)
您可以尝试com.google.common.truth.Correspondence
。
public class MatchesCorrespondence<A> extends Correspondence<A, String> {
@Override
public boolean compare(@Nullable A actual, @Nullable String expected) {
return actual != null && actual.toString().matches(expected);
}
// other overrides
}
然后你可以断言:
assertThat(list)
.comparingElementsUsing(new MatchesCorrespondence<>())
.contains("Foo .* Bar");