Reputation: 13
using hamcrest and java 8, what's the easiest way (one liner) to assert that a collection contains a element with a specific set of requirements? I'd like to be able to retrieve the element, if it exists, and perform some tests on it, in one go (and in a readable form). Or maybe at least assert that a list contains a specific element, and return it in one go, so that I can then perform some tests on it.
Upvotes: 0
Views: 884
Reputation: 7076
With AssertJ I would try one of these:
anySatisfy
(takes a Consumer
to express the requirements ending with informative errors)anyMatch
(takes a Predicate
, error is less informative)hasOnlyOneElementSatisfying
(takes a Consumer
, work iif exactly one element matches)haveAtLeastOne
(takes a Condition
which is a like an Hamcrest macther)To get a one liner, it is likely that you will have to extract the Condition
, Consumer
or Predicate
to a variable/field instead of inlining it.
Follow the javadoc links, they all have code examples showing how to they can be used. You can also have a look at the assertj-examples project, a showcase of AssertJ.
Hope that helps
Upvotes: 2