Posted In: Hamcrest, Junit, Testing

How to create own custom Hamcrest matcher using TypeSafeMatcher

Usecase – Create own custom Hamcrest matcher using TypeSafeMatcher

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.Description
org.hamcrest.TypeSafeMatcher

Custom substring matcher

package com.example.testing.hamcrest;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

public class TestHamcrestMatcher1 extends TypeSafeMatcher<String> {

	private final String substring;

	public TestHamcrestMatcher1(final String substring) {
		this.substring = substring;
	}

	@Override
	public void describeTo(final Description description) {
		description.appendText("matches substring=`" + substring + "`");
	}

	@Override
	public boolean matchesSafely(final String string) {
		return string.contains(substring);
	}

	public static TestHamcrestMatcher1 matchesSubstring(final String substring) {
		return new TestHamcrestMatcher1(substring);
	}
}

Custom sublist matcher

package com.example.testing.hamcrest;

import java.util.List;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

public class TestHamcrestMatcher2 extends TypeSafeMatcher<List<String>> {

	private final List<String> sublist;

	public TestHamcrestMatcher2(final List<String> sublist) {
		this.sublist = sublist;
	}

	@Override
	public void describeTo(final Description description) {
		description.appendText("matches sublist=`" + sublist + "`");
	}

	@Override
	public boolean matchesSafely(final List<String> list) {
		return list.containsAll(sublist);
	}

	public static TestHamcrestMatcher2 matchesSublist(
	        final List<String> sublist) {
		return new TestHamcrestMatcher2(sublist);
	}
}

Custom matcher test

package com.example.testing.hamcrest;

import static org.junit.Assert.assertThat;

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

import org.junit.Test;

public class TestHamcrestMatcher {

	@Test
	public void testSubStringMatcher() throws Exception {
		String actual = "aaabbbaaaa";
		assertThat(actual, TestHamcrestMatcher1.matchesSubstring("aaa"));
	}

	@Test
	public void testSubListMatcher() throws Exception {
		List<String> actual = new ArrayList<String>();
		actual.add("aa");
		actual.add("bb");
		actual.add("cc");

		List<String> sublist = new ArrayList<String>();
		sublist.add("aa");
		sublist.add("bb");
		sublist.add("cc");

		assertThat(actual, TestHamcrestMatcher2.matchesSublist(sublist));
	}
}

by , on August 21st, 2017

  • Categories