Posted In: Hamcrest, Junit, Testing

How to unit test a string array – JUnit + Hamcrest

Usecase – You need to unit test string 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 static org.hamcrest.CoreMatchers.startsWith;

import java.util.Arrays;

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

public class TestHamcrestCollection {

	@Rule
	public ErrorCollector collector = new ErrorCollector();

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

		String[] actual = { "a", "b", "cde" };

		// positive
		collector.checkThat(actual,
		        is(IsArray.array(equalTo("a"), equalTo("b"), equalTo("cde"))));
		// negative
		collector.checkThat(actual,
		        is(IsArray.array(equalTo("a"), equalTo("b"))));
		// negative
		collector.checkThat(actual,
		        is(IsArray.array(equalTo("a"), equalTo("b"), equalTo("d"))));
		// positive
		collector.checkThat(Arrays.asList(actual), hasItems("a", "b"));
		// positive
		collector.checkThat(Arrays.asList(actual), hasItems(equalTo("a")));
		// negative
		collector.checkThat(Arrays.asList(actual), hasItems(equalTo("d")));
		// positive
		collector.checkThat(actual,
		        IsArrayContaining.hasItemInArray(startsWith("c")));
	}

}

Output

java.lang.AssertionError: 
Expected: is ["a", "b"]
     but: array length was 3
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.junit.Assert.assertThat(Assert.java:956)

java.lang.AssertionError: 
Expected: is ["a", "b", "d"]
     but: element 2 was "cde"
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.junit.Assert.assertThat(Assert.java:956)

java.lang.AssertionError: 
Expected: (a collection containing "d")
     but: a collection containing "d" was "a", was "b", was "cde"
	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)

Tags:

by , on August 12th, 2017

  • Categories