Reputation: 2803
With Assertj, I can use anyMatch
to test if a collection has at least one element matching a predicate, e.g.
var list = List.of("abc", "xyz")
assertThat(list).anyMatch(element -> element.endsWith("xyz"));
But how do I test if a collection has exactly one element that matches a predicate?
Upvotes: 4
Views: 2163
Reputation: 5443
How about using the filter? https://github.com/assertj/assertj-core/blob/9eceff23e5b019af3d09c3e9bbc58126d51c02b6/src/main/java/org/assertj/core/api/AbstractIterableAssert.java#L3283
var list = List.of("a", "b", "c!");
assertThat(list)
.filteredOn(element -> element.endsWith("!"))
.hasSize(1);
Upvotes: 10