对 Iterable 中的元素进行断言

Making assertions about elements in an Iterable

我有一个对象列表,我想对对象本身进行真值断言,但我看不出有任何合理的方式来表达比等式断言更复杂的任何东西。我设想的是这样的:

assertThat(list).containsElementThat().matches("Foo .* Bar");

假设这在 Truth 中不可用,那么表达这种东西的最 Truth-y 方式是什么?如果我知道我正在查看列表中的哪个位置,我可以这样说:

assertThat(list).hasSize(Math.max(list.size(), i));
assertThat(list.get(i)).matches("Foo .* Bar");

但是(除了有点 hacky 之外)这只有在我事先知道 i 的情况下才有效,并且不适用于任意可迭代对象。有什么比自己做更好的解决方案吗?

你可以 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");