Posted In: Hamcrest, Junit, Testing

How to unit test list is empty – JUnit + Hamcrest

Usecase – You need to unit test if list is empty. Hamcrest library may be useful to achieve that

Hamcrest 1.3

<dependency>
	<groupId>org.hamcrest</groupId>
	<artifactId>hamcrest-library</artifactId>
	<version>1.3</version>
	<scope>test</scope>
</dependency>

Classes used from Hamcrest

org.hamcrest.collection.IsCollectionWithSize
org.hamcrest.number.OrderingComparison

Using ErrorCollector so that execution continues even if assert statement fails.

package com.example.testing.hamcrest;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;

import java.util.ArrayList;
import java.util.List;

import org.hamcrest.collection.IsCollectionWithSize;
import org.hamcrest.number.OrderingComparison;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class TestHamcrestCollection7 {

	@Rule
	public ErrorCollector collector = new ErrorCollector();

	@Test
	public void testListEmpty() {

		try {
			List<String> actual1 = new ArrayList<String>();

			List<String> actual2 = new ArrayList<String>();
			actual2.add("test");

			// Positive
			collector.checkThat(actual1.isEmpty(), is(true));

			// Positive
			collector.checkThat(actual2,
			        is(not(org.hamcrest.Matchers.empty())));

			// Positive
			collector.checkThat(actual1, is(IsCollectionWithSize.hasSize(0)));

			// Positive
			collector.checkThat(actual2, IsCollectionWithSize
			        .hasSize(OrderingComparison.greaterThan(0)));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

by , on August 18th, 2017

  • Categories