Explain Codes LogoExplain Codes Logo

Checking that a List is not empty in Hamcrest

java
assertions
hamcrest
testing
Alex KataevbyAlex KataevยทFeb 1, 2025
โšกTLDR

If you need a Hamcrest shortcut to determine if a list is not empty, the hasItem or hasItems matchers provide succinct options:

import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; List<String> myList = Arrays.asList("item1"); assertThat(myList, hasItem(anything())); // Asserts that myList contains at least one item... sneaky huh ๐Ÿ˜‰

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:

assertThat(myList, is(not(empty())));

Make sure you opt for the correct static imports:

import static org.hamcrest.Matchers.empty; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not;

Dealing with collections cast

Working with older versions of Hamcrest (say, 1.2) requires some attention to casting:

assertThat((Collection)myList, is(not(empty())));

Asserting a list's size

If your use case calls for ensuring a list has more than a certain size, pair hasSize with greaterThan:

assertThat(myList, hasSize(greaterThan(0))); // I want it taller than my 0ft garden gnome!

Don't forget your static imports for greaterThan:

import static org.hamcrest.number.OrderingComparison.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():

assertEquals(false, myList.isEmpty()); // "Excuse me, do you have time to speak about our lord and savior 'equals' method?"

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:

assertThat(myList, hasItems("item1", "item2")); // "Hey list, got item1 and item2?"

Custom matchers for specified validations

Sometimes, the built-in matchers won't work. To assert complex scenarios, create a custom matcher:

assertThat(myList, new CustomMatcher<List<String>>() { // Custom matching logic here });

Ordered list assertions

To assert the order of items in a list, use contains or containsInAnyOrder:

assertThat(myList, contains("item1", "item2")); // "I like my items in order, thankyouverymuch." assertThat(myList, containsInAnyOrder("item2", "item1")); // "Ehh...they can stroll in however they prefer"

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:

assertThat(myList, not(isEmptyOrNullString()));

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:

assertThat(myList, containsInAnyOrder(expectedElements)); // We're not just about quantity, we care for quality!

Null? Not on my watch!

Before checking for emptiness, ward off null values:

assertThat(myList, is(notNullValue())); // You can't hide from me, Null! assertThat(myList, is(not(empty()))); // The same applies to you, Emptiness!

Safeguarding against both null and emptiness presents a solid defense for your assertions.