3

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?

Antonio Dragos
  • 1,973
  • 2
  • 29
  • 52

1 Answers1

10

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);

Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23
  • 1
    that seems to work, although I would expect there to be a less verbose syntax – Antonio Dragos Nov 20 '20 at 14:46
  • 3
    I guess there are lots of possible ways people might assert the collection. Perhaps raise a PR against assertJ with your suggested alternative `hasOneMatch` or similar...? – Ashley Frieze Nov 20 '20 at 14:50
  • Sorry guyz but your solution cannot compile. A lambda expression can only be used to implement a functional interface. However AssertJ Condition is a class: https://github.com/assertj/assertj/blob/9d7c08c9212993a81ed3eb605b771e48e6ae6819/assertj-core/src/main/java/org/assertj/core/api/Condition.java#L33 Hence, your code must result in a compiler error: `incompatible types: Condition is not a functional interface` – Jörg Aug 10 '23 at 21:03
  • there is ```filteredOn(Predicate)``` which can be implemented via a lambda – Ubeogesh Aug 23 '23 at 10:58