2

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?

Naftali
  • 144,921
  • 39
  • 244
  • 303
dimo414
  • 47,227
  • 18
  • 148
  • 244

1 Answers1

3

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");
dimo414
  • 47,227
  • 18
  • 148
  • 244
vsminkov
  • 10,912
  • 2
  • 38
  • 50
  • Oh interesting, I'd not seen the `Correspondence` before! This still seems odd though; for instance the imaginary `assertThat(list).containsElementThat().hasLength(5)` would become `assertThat(list).comparingElementsUsing(stringLengthCorrespondence).contains(5)` which is rather difficult to parse. Admittedly it's still much better than re-implementing everything yourself. – dimo414 Aug 11 '16 at 18:54
  • @dimo414 that's true. but you also can try to make a pull request to make things better :) – vsminkov Aug 11 '16 at 19:00
  • 1
    Never fear, that's my plan :) just trying to understand the state of the world before I do so. – dimo414 Aug 11 '16 at 19:25