JUnit 4 with Hamcrest

Hamcrest and open source library of nice syntactic matchers that was pulled into JUnit 4 as in 2007. My anecdotal evidence having mentored a number of development groups on JUnit testing is that the old standby assertEquals is still the default assertion that’s used in practice. I’ve given hands on demonstrations a number of times now and I wanted to put together a list of example tests showing the uses of the various core assertions now available. There is a decent tutorial on using Hamcrest, but this will focus primarily on the core assertions it adds to JUnit.

A good starting place is the assertThat() method that can now almost always be used in place of the traditional assertEquals(). assertThat() can be found in org.junit.Assert, but it defines using Hamcrest matchers in the signature:

static <T> void assertThat(T actual, org.hamcrest.Matcher<T> matcher)

assertThat() is a drop in replacement for the traditional assertEquals() style assertions that generally reads more like a specification or the more modern BDD style. Basically it just reads better with something like this:

assertThat("Hello World", is(equalTo(Greeter.greeting());

This would be in contrast to:

assertEqual(Greeter.greetings(), "Hello World");

Admittedly the new assertThat() style is a bit more verbose, but it readability is significantly enhanced. Code gets read a lot more often that it’s written so readability of tests is important as well.

These are the core methods contained in org.hamcrest.CoreMatchers class they all just get used by means of a static import of org.hamcrest.CoreMatchers. They cover the following static methods in alphabetical order:

  • allOf()
  • any()
  • anyOf()
  • anything()
  • describedAs()
  • equalTo()
  • instanceOf()
  • is()
  • not()
  • notNullValue()
  • nullValue()
  • sameInstance()

allOf()

allOf() is a simple assertion that just says all of the matcher arguments must be true. So in this example the string “Hello” must be not be null, an instance of String, and equal to the value “Hello”.

1
2
3
4
@Test
public void allOfExampleShowsAllMatchersMustAllBeTrue() throws Exception {
  assertThat("Hello", is(allOf(notNullValue(), instanceOf(String.class), equalTo("Hello"))));
}

A negative example might look like this:

1
2
3
4
@Test
public void allOfExampleShowsFailingIfOneMatcherDoesNotMatch() throws Exception {
  assertThat("Hello", is(not(allOf(notNullValue(), instanceOf(Integer.class)))));
}

any()

This matcher just checks that the actual result is a class of a certain type. I don’t have any great use case for using this, but its included for completeness.

1
2
3
4
@Test
public void anyExampleChecksThatClassIsOfSameType() throws Exception {
  assertThat("Hello", is(any(String.class)));
}

In addition any superclass works as well:

1
2
3
4
@Test
public void anyExampleShowsStringIsAlsoAnObject() throws Exception {
  assertThat("Hello", is(any(Object.class)));
}

anyOf()

If any of the matchers are true this assertion will pass. In the following example on the instanceOf(String.class) is true, but it still passes.

1
2
3
4
@Test
public void anyOfExampleReturnsTrueIfOneMatches() throws Exception {
  assertThat("Hello", is(anyOf(nullValue(), instanceOf(String.class), equalTo("Goodbye"))));
}

And the negative case where all the matchers are false:

1
2
3
4
@Test
public void anyOfExampleFailingIfAllMatchersAreFalse() throws Exception {
  assertThat("Hello", is(not(anyOf(nullValue(), instanceOf(Integer.class), equalTo("Goodbye")))));
}

anything()

This matcher will always evaluates to true. Again don’t have a good example use case for this:

1
2
3
4
@Test
public void anythingExampleAlwaysReturnsTrue() throws Exception {
  assertThat("Hello", is(anything()));
}

The implementation code is really this simple:

1
2
3
4
// From the hamcrest IsAnything class
public boolean matches(Object o) {
  return true;
}

describeAs()

This allows you to override the default description for a matcher. Not a lot of use cases for this.

1
2
3
4
5
public void describedAsExample() throws Exception {
  Matcher< ?> matcher = describedAs("My Description", anything());
  Description description = new StringDescription().appendDescriptionOf(matcher);
  assertThat("My Description", is(description.toString()));
}

equalTo

This is one of the core matchers that duplicates the functionality of the old assertEquals().

1
2
3
4
@Test
public void equalToExampleAddingTwoPlusTwo() throws Exception {
  assertThat(2 + 2, is(equalTo(4)));
}

instanceOf

instanceOf() checks that you have an instance of a particular type:

1
2
3
4
@Test
public void instanceOfExampleForString() throws Exception {
  assertThat("Hello", is(instanceOf(String.class)));
}

is()

One of my favorite matchers, primarily used for syntactic sugar to increase the readability. The following silly example shows its use as syntactic sugar by using it three times in a row:

1
2
3
4
@Test
public void isExampleShortCutAsJustSyntacticSugarUsedThreeTimes() throws Exception {
  assertThat("Hello", is(is(is(notNullValue()))));
}

It can also be used as a shortcut for instanceOf when you pass in a class argument:

1
2
3
4
5
@Test
public void isExampleShortCutForIsInstanceOfClass() throws Exception {
  assertThat("Hello", is(String.class));
  assertThat("Hello", instanceOf(String.class));
}

And there is a shortcut for equalsTo as well where you pass in any value:

1
2
3
4
5
@Test
public void isExampleShortCutForIsEqualTo() throws Exception {
  assertThat("Hello", is("Hello"));
  assertThat("Hello", equalTo("Hello"));
}

not()

not() just reverses the outcome of a matcher:

1
2
3
4
@Test
public void notExampleJustInvertsExpression() throws Exception {
  assertThat("Hello", is(not(instanceOf(Integer.class))));
}

notNullValue()

Simply does a null check.

1
2
3
4
@Test
public void notNullValueExampleForString() throws Exception {
  assertThat("Hello", is(notNullValue()));
}

It can also do a type check as well by passing in a class argument:

1
2
3
4
@Test
public void notNullValueExampleForAClass() throws Exception {
  assertThat("Hello", is(notNullValue(Object.class)));
}

nullValue

Assert a null value:

1
2
3
4
@Test
public void nullValueExampleWithANull() throws Exception {
  assertThat(null, is(nullValue()));
}

Assert a null value with a type check:

1
2
3
4
5
@Test
public void nullValueExampleWithANullType() throws Exception {
  Integer nothing = null;
  assertThat(nothing, is(nullValue(Integer.class)));
}

sameInstance()

Checks if the two object references are the same using the == operator:

1
2
3
4
5
6
@Test
public void sameInstanceExample() throws Exception {
  Object object = new Object();
  Object sameObject = object;
  assertThat(object, is(sameInstance(sameObject)));
}

Example Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package com.edgibbs.junit.example;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

public class HamcrestExamples {

  @Test
  public void allOfExampleShowsAllMatchersMustAllBeTrue() throws Exception {
    assertThat("Hello", is(allOf(notNullValue(), instanceOf(String.class), equalTo("Hello"))));
  }

  @Test
  public void allOfExampleShowsFailingIfOneMatcherDoesNotMatch() throws Exception {
    assertThat("Hello", is(not(allOf(notNullValue(), instanceOf(Integer.class)))));
  }

  @Test
  public void anyExampleChecksThatClassIsOfSameType() throws Exception {
    assertThat("Hello", is(any(String.class)));
  }

  @Test
  public void anyExampleShowsStringIsAlsoAnObject() throws Exception {
    assertThat("Hello", is(any(Object.class)));
  }

  @Test
  public void anyOfExampleReturnsTrueIfOneMatches() throws Exception {
    assertThat("Hello", is(anyOf(nullValue(), instanceOf(String.class), equalTo("Goodbye"))));
  }

  @Test
  public void anyOfExampleFailingIfAllMatchersAreFalse() throws Exception {
    assertThat("Hello", is(not(anyOf(nullValue(), instanceOf(Integer.class), equalTo("Goodbye")))));
  }

  @Test
  public void anythingExampleAlwaysReturnsTrue() throws Exception {
    assertThat("Hello", is(anything()));
  }

  // Feels very esoteric and not for typical usage used to override the description
  @Test
  public void describedAsExample() throws Exception {
    Matcher< ?> matcher = describedAs("My Description", anything());
    Description description = new StringDescription().appendDescriptionOf(matcher);
    assertThat("My Description", is(description.toString()));
  }

  @Test
  public void equalToExampleAddingTwoPlusTwo() throws Exception {
    assertThat(2 + 2, is(equalTo(4)));
  }

  @Test
  public void instanceOfExampleForString() throws Exception {
    assertThat("Hello", is(instanceOf(String.class)));
  }

  @Test
  public void isExampleShortCutForIsInstanceOfClass() throws Exception {
    assertThat("Hello", is(String.class));
    assertThat("Hello", instanceOf(String.class));
  }

  @Test
  public void isExampleShortCutAsJustSyntacticSugarUsedThreeTimes() throws Exception {
    assertThat("Hello", is(is(is(notNullValue()))));
  }

  @Test
  public void isExampleShortCutForIsEqualTo() throws Exception {
    assertThat("Hello", is("Hello"));
    assertThat("Hello", equalTo("Hello"));
  }

  @Test
  public void notExampleJustInvertsExpression() throws Exception {
    assertThat("Hello", is(not(instanceOf(Integer.class))));
  }

  @Test
  public void notNullValueExampleForString() throws Exception {
    assertThat("Hello", is(notNullValue()));
  }

  @Test
  public void notNullValueExampleForAClass() throws Exception {
    assertThat("Hello", is(notNullValue(Object.class)));
  }

  @Test
  public void nullValueExampleWithANull() throws Exception {
    assertThat(null, is(nullValue()));
  }

  @Test
  public void nullValueExampleWithANullType() throws Exception {
    Integer nothing = null;
    assertThat(nothing, is(nullValue(Integer.class)));
  }

  @Test
  public void sameInstanceExample() throws Exception {
    Object object = new Object();
    Object sameObject = object;
    assertThat(object, is(sameInstance(sameObject)));
  }

}