Posted In: Hamcrest, Junit, Testing

How to unit test a Integer array – JUnit + Hamcrest

Usecase – You need to unit test Integer array output and write multiple scenarios to test the data. 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.IsArray;
org.hamcrest.collection.IsArrayContaining;
org.junit.rules.ErrorCollector;

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

package com.example.testing.hamcrest;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;

import java.util.Arrays;

import org.hamcrest.collection.IsArray;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class TestHamcrestCollection2 {

	@Rule
	public ErrorCollector collector = new ErrorCollector();

	@Test
	@SuppressWarnings(value = { "unchecked" })
	public void testIsArray() {

		Integer[] actual = { 1, 2, 3 };

		// positive
		collector.checkThat(actual,
		        is(IsArray.array(equalTo(1), equalTo(2), equalTo(3))));
		// negative
		collector.checkThat(actual, is(IsArray.array(equalTo(1), equalTo(2))));
		// negative
		collector.checkThat(actual,
		        is(IsArray.array(equalTo(1), equalTo(2), equalTo(4))));
		// positive
		collector.checkThat(Arrays.asList(actual), hasItems(1, 2));
		// positive
		collector.checkThat(Arrays.asList(actual), hasItems(equalTo(1)));
		// negative
		collector.checkThat(Arrays.asList(actual), hasItems(equalTo(4)));
	}

}

Output

java.lang.AssertionError: 
Expected: is [<1>, <2>]
     but: array length was 3
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.junit.Assert.assertThat(Assert.java:956)
	at org.junit.rules.ErrorCollector$1.call(ErrorCollector.java:65)

java.lang.AssertionError: 
Expected: is [<1>, <2>, <4>]
     but: element 2 was <3>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.junit.Assert.assertThat(Assert.java:956)
	at org.junit.rules.ErrorCollector$1.call(ErrorCollector.java:65)

java.lang.AssertionError: 
Expected: (a collection containing <4>)
     but: a collection containing <4> was <1>, was <2>, was <3>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.junit.Assert.assertThat(Assert.java:956)
	at org.junit.rules.ErrorCollector$1.call(ErrorCollector.java:65)
	at org.junit.rules.ErrorCollector.checkSucceeds(ErrorCollector.java:78)

Tags:

by , on August 12th, 2017

  • Categories