JUnit – How to test a List

First, exclude the JUnit bundled copy of hamcrest-core, and include the useful hamcrest-library, it contains many useful methods to test the List data type.

pom.xml

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.hamcrest</groupId>
					<artifactId>hamcrest-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!-- This will get hamcrest-core automatically -->
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-library</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

1. Assert List String

Check the package org.hamcrest.collection, it contains many useful methods to test a Collection or List

ListTest.java

package com.mkyong;

import org.junit.Test;

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

import org.hamcrest.collection.IsEmptyCollection;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.MatcherAssert.assertThat;

public class ListTest {

    @Test
    public void testAssertList() {

        List<String> actual = Arrays.asList("a", "b", "c");
        List<String> expected = Arrays.asList("a", "b", "c");
		
		//All passed / true
		
        //1. Test equal.
        assertThat(actual, is(expected));

        //2. If List has this value?
        assertThat(actual, hasItems("b"));

        //3. Check List Size
        assertThat(actual, hasSize(3));

        assertThat(actual.size(), is(3));

        //4.  List order

        // Ensure Correct order
        assertThat(actual, contains("a", "b", "c"));

        // Can be any order
        assertThat(actual, containsInAnyOrder("c", "b", "a"));

        //5. check empty list
        assertThat(actual, not(IsEmptyCollection.empty()));

        assertThat(new ArrayList<>(), IsEmptyCollection.empty());

    }

}

2. Assert List Integer

Check the package org.hamcrest.number, it has methods to assert numbers.

ListTest.java

package com.mkyong;

import org.junit.Test;

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

import org.hamcrest.collection.IsEmptyCollection;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;

import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
import static org.hamcrest.number.OrderingComparison.lessThan;

import static org.hamcrest.MatcherAssert.assertThat;

public class ListTest {

    @Test
    public void testAssertList() {

        List<Integer> actual = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5);

        //All passed / true

        //1. Test equal.
        assertThat(actual, is(expected));

        //2. Check List has this value
        assertThat(actual, hasItems(2));

        //3. Check List Size
        assertThat(actual, hasSize(4));

        assertThat(actual.size(), is(5));

        //4.  List order

        // Ensure Correct order
        assertThat(actual, contains(1, 2, 3, 4, 5));

        // Can be any order
        assertThat(actual, containsInAnyOrder(5, 4, 3, 2, 1));

        //5. check empty list
        assertThat(actual, not(IsEmptyCollection.empty()));

        assertThat(new ArrayList<>(), IsEmptyCollection.empty());

		//6. Test numeric comparisons
        assertThat(actual, everyItem(greaterThanOrEqualTo(1)));

        assertThat(actual, everyItem(lessThan(10)));

    }


}
Note
Both org.hamcrest.collection and org.hamcrest.number are belong to hamcrest-library

3. Assert List Objects

ListTest.java

package com.mkyong;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;

public class ListTest {

    @Test
    public void testAssertList() {

        List<Fruit> list = Arrays.asList(
                new Fruit("Banana", 99), 
                new Fruit("Apple", 20)
        );

        //Test equals
        assertThat(list, hasItems(
                new Fruit("Banana", 99),
                new Fruit("Apple", 20)
        ));

        assertThat(list, containsInAnyOrder(
                new Fruit("Apple", 20),
                new Fruit("Banana", 99)
        ));

        //Test class property, and its value
        assertThat(list, containsInAnyOrder(
                hasProperty("name", is("Apple")),
                hasProperty("name", is("Banana"))
        ));

    }

    public class Fruit {

        public Fruit(String name, int qty) {
            this.name = name;
            this.qty = qty;
        }

        private String name;
        private int qty;

        public int getQty() {
            return qty;
        }

        public void setQty(int qty) {
            this.qty = qty;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        //Test equal, override equals() and hashCode()
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Fruit fruit = (Fruit) o;
            return qty == fruit.qty &&
                    Objects.equals(name, fruit.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, qty);
        }
    }


}

Do share your List testing examples below :)

References

  1. Hamcrest official site
  2. Matchers of arrays and collections – org.hamcrest.collection
  3. Matchers that perform numeric comparisons – org.hamcrest.number
  4. Maven and JUnit example
  5. JUnit – How to test a Map
  6. Java – How to override equals and hashCode
  7. JUnit – Assert if a property exists in a class

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
9 Comment threads
0 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
9 Comment authors
SachinzikyoubiihebrobertoMorjan Recent comment authors
newest oldest most voted
roberto
Guest
roberto

import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; it’s deprecated!!

zikyoubi
Guest
zikyoubi

hasItems is deprecated ..

Sachin
Guest
Sachin

How to check if all elements of the list have same value for a variable. For example, if all objects in a list have “name” to be “Banana”

iheb
Guest
iheb

roberto not all containsInAnyOrder are deprecated. containsInAnyOrder(Matcher itemMatcher) is deprecated but containsInAnyOrder(Matcher… itemMatchers) is not. See http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#hasItem(org.hamcrest.Matcher)

Morjan
Guest
Morjan

Super tutorials on JUnit, was my weakness from long time. will be confident on it after.

venkatesh
Guest
venkatesh

{“studentIds”:[1,2]} if this is json string then how to write junit test cases for the array of elements

Ritesh
Guest
Ritesh

Thanks for the example.
One typo I believe –

//3. Check List Size
assertThat(actual, hasSize(4));

this should be:

//3. Check List Size
assertThat(actual, hasSize(5));

i.e. the list size is 5 in the test.

essymizo
Guest
essymizo

The best !! Thanks

John
Guest
John

thanks