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.
Asked
Active
Viewed 746 times
1 Answers
2
With AssertJ I would try one of these:
anySatisfy
(takes aConsumer
to express the requirements ending with informative errors)anyMatch
(takes aPredicate
, error is less informative)hasOnlyOneElementSatisfying
(takes aConsumer
, work iif exactly one element matches)haveAtLeastOne
(takes aCondition
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

Joel Costigliola
- 6,308
- 27
- 35