2

オブジェクトのリストがあり、オブジェクト自体について Truth スタイルのアサーションを作成したいと考えていますが、等価アサーションよりも複雑なものを表現する合理的な方法が見つかりません。私は次のようなものを想定しています:

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

これが Truth で利用できないと仮定すると、このようなことを表現するための最も Truth-y な方法は何ですか? リスト内のどの位置を探しているかがわかっていれば、次のように言えます。

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

しかし、(ややハックであることに加えて)事前に知っている場合にのみ機能iし、任意のイテラブルでは機能しません。これを自分で行うよりも良い解決策はありますか?

4

1 に答える 1

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");
于 2016-08-11T18:27:14.437 に答える