JUnit 4 Showcase – assertThat and Hamcrest Matchers

Surely assertEquals() can get you far but you will be amazed with the versatility of assertThat() combined with the expressive and human friendly Matchers of the Hamcrest library.

The needed static imports in your JUnit 4 test case:

import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.CoreMatchers.*;

You could use the is() and not() matchers like so:

	@Test
	public void assertThat1(){
		double d = 1.3;
		assertThat(d, is(1.3));
		assertThat(d, is(not(1.4)));
	}

or equalTo():

	@Test
	public void assertThat2(){
		String str="test";
		assertThat(str, equalTo("test"));
		assertThat(str, not(equalTo("anotherTest")));
	}

or anyOf():

	@SuppressWarnings("unchecked")
	@Test
	public void assertThat3(){
		String str="test";
		assertThat(str, anyOf(is("test"), is("this"), is("that")));
		assertThat(str, not(anyOf(is("tasty"), is("this"), is("that"))));
	}

or lessThan() and hasItem() for Collections:

	@SuppressWarnings("serial")
	@Test
	public void assertThatCollections1(){
		List<String> list = new ArrayList<String>(){{add("one");add("two");add("three");}};
		assertThat(list, hasItem("two"));
		assertThat(list, not(hasItem("ttwo")));
	}
	
	@SuppressWarnings("serial")
	@Test
	public void assertThatCollections2(){
		List<Integer> list = new ArrayList<Integer>(){{add(1);add(2);add(3);}};
		assertThat(list, not(hasItem(lessThan(0))));
	}

or hasKey() and hasValue() particularly for Maps:

	@Test
	public void assertThatMaps1(){
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("one", 1);
		map.put("two", 2);
		map.put("three", 3);
		assertThat(map, Matchers.<String,Integer>hasKey("one"));
		assertThat(map, Matchers.<String,Integer>hasValue(2));
	}

A thing to note in the above example is the way we need to explicitly define the types on the key/value Map pair before summoning hasKey() or hasValue(), a bit weird why type inference didn’t help us there.

Finally we could even query properties of Java Beans:

@Test
	public void assertThatProperty1(){
		
		class Bean<T> {
			private T t;
			public void setT(T t){this.t = t;}
			public T getT(){return this.t;}
		}
		
		Bean<String> myBean = new Bean<String>();
		myBean.setT("hi");
		assertThat(myBean, hasProperty("t",is("hi")));
		assertThat(myBean, hasProperty("t",startsWith("h")));
	}

The code can be found in this Gitbub repository.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s