Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert list contains exactly one element satisfying condition

In my JUnit test I want to assert that a list contains exactly one element satisfying a given condition (there can be many elements in the list, but only one should satisfy the condition). I wrote the code below, but I was wondering if it's possible to get rid of the "new Condition<>"-part and use a "pure" lambda? Or are there other, more elegant ways to accomplish what I am trying to do?

class Foo {
  String u;

  Foo(String u) { this.u = u; }

  String getIt() { return u; }
}

@Test
public void testIt() {
  List<Foo> list = Lists.newArrayList(new Foo("abc"), new Foo("xyz"));

  assertThat(list)
        .haveExactly(1, new Condition<>(
                x -> "xyz".equals(x.getIt()),
                "Fail"));
}
like image 389
Eric Lilja Avatar asked Sep 11 '25 16:09

Eric Lilja


1 Answers

This should work (but I haven't tested it):

assertThat(list).extracting(Foo::getIt)
                .containsOnlyOnce("xyz");
like image 181
assylias Avatar answered Sep 14 '25 04:09

assylias