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"));
}
This should work (but I haven't tested it):
assertThat(list).extracting(Foo::getIt)
.containsOnlyOnce("xyz");