Checking that a List is not empty in Hamcrest
If you need a Hamcrest shortcut to determine if a list is not empty, the hasItem
or hasItems
matchers provide succinct options:
This statement asserts that myList
holds at least one element that matches any condition.
Ways to Assert a Non-Empty List
Approaching non-emptiness directly
Here, we'll leverage the use of is
, not
, and empty
for a readable and intent-oriented syntax:
Make sure you opt for the correct static imports:
Dealing with collections cast
Working with older versions of Hamcrest (say, 1.2) requires some attention to casting:
Asserting a list's size
If your use case calls for ensuring a list has more than a certain size, pair hasSize
with greaterThan
:
Don't forget your static imports for greaterThan
:
Moving beyond Hamcrest: The Java way
Sans Hamcrest, a distilled option for asserting a non-empty list is assertEquals
which compares false
with myList.isEmpty()
:
Using traditional Java assertions is equivalent to a layman's language of code.
Detailed Hamcrest Techniques for Lists
Asserting specific elements
If you need to ensure specific elements are in the list, hasItems
comes to your aid:
Custom matchers for specified validations
Sometimes, the built-in matchers won't work. To assert complex scenarios, create a custom matcher:
Ordered list assertions
To assert the order of items in a list, use contains
or containsInAnyOrder
:
Mastering Matchers: The Nuances
The curious case of any
and anything
The matchers any
and anything
come across as mysterious beasts:
any(Class<T>)
: checks for an item = exists + type, sort of a picky eater.anything()
: is a freeloading matcher that returns true for any item, it's got no chill.
Expressiveness for the win
Well-formulated assertions act as self-documenting code. Hamcrest allows for such logical, natural assertions:
This assertion tells you at face value that the list should neither be empty nor house a null/empty string.
Hands-on: Avoiding common mistakes
Incorrect static import? No, thanks!
Ensure you import the right matchers to steer clear of exasperating compilation conflicts.
Are the actual list contents up to snuff?
Beyond checking for non-emptiness, do validate the list contents:
Null? Not on my watch!
Before checking for emptiness, ward off null values:
Safeguarding against both null
and emptiness presents a solid defense for your assertions.
Was this article helpful?