I have a list of objects and I would like to make Truth-style assertions about the objects themselves, but I don't see any reasonable way to express anything more complex than equality assertions. I'm envisioning something like:
assertThat(list).containsElementThat().matches("Foo .* Bar");
Assuming that this isn't available in Truth, what's the most Truth-y way to express something like this? If I knew which position in the list I was looking I could say something like:
assertThat(list).hasSize(Math.max(list.size(), i));
assertThat(list.get(i)).matches("Foo .* Bar");
But (in addition to being somewhat hacky) that only works if I know i
in advance, and doesn't work for arbitrary iterables. Is there any solution better than just doing this myself?
You can give com.google.common.truth.Correspondence
a try.
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
}
Then you can assert like that:
assertThat(list)
.comparingElementsUsing(new MatchesCorrespondence<>())
.contains("Foo .* Bar");