Posted In: Hamcrest, Junit, Testing

How to unit test String output – JUnit + Hamcrest

Usecase – You need to unit test String output. 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.CoreMatchers.allOf
org.hamcrest.CoreMatchers.anyOf

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

package com.example.testing.hamcrest;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.anyOf;

import java.util.Arrays;

import org.hamcrest.core.StringContains;
import org.hamcrest.text.IsEmptyString;
import org.hamcrest.text.StringContainsInOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class TestHamcrestString {

	@Rule
	public ErrorCollector collector = new ErrorCollector();

	@Test
	public void testString() {

		try {
			String actual = "a ab abc";

			// Positive
			collector.checkThat(actual, StringContainsInOrder
			        .stringContainsInOrder(Arrays.asList("a", "ab", "abc")));

			// Positive
			collector.checkThat(actual, StringContains.containsString("abc"));

			// Positive
			collector.checkThat(actual,
			        org.hamcrest.CoreMatchers.containsString("abc"));

			// Positive
			collector.checkThat("", IsEmptyString.isEmptyString());

			// Positive
			collector.checkThat("", IsEmptyString.isEmptyOrNullString());

			// Positive
			collector.checkThat(actual,
			        allOf(org.hamcrest.CoreMatchers.containsString("a"),
			                org.hamcrest.CoreMatchers.containsString("ab"),
			                org.hamcrest.CoreMatchers.containsString("abc")));

			// Positive
			collector.checkThat(actual,
			        anyOf(org.hamcrest.CoreMatchers.containsString("a"),
			                org.hamcrest.CoreMatchers.containsString("cd"),
			                org.hamcrest.CoreMatchers.containsString("ef")));

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

by , on August 18th, 2017

  • Categories