- Objects:
equalTo, hasToString, instanceOf, isCompatibleType, notNullValue, nullValue, sameInstance
- Text:
equalToIgnoringCase, equalToIgnoringWhiteSpace, containsString, endsWith, startsWith
- Numbers:
closeTo, greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo
- Logical:
allOf, anyOf, not
- Collections:
array
(compare an array to an array of matchers),hasEntry, hasKey, hasValue, hasItem, hasItems, hasItemInArray
The following code sample shows a few examples of using Hamcrest in a JUnit 5 test class.
Listing 1. Using Hamcrest in a JUnit 5 test class (HamcrestDemoTest.java)
package com.javaworld.geekcap.hamcrest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
class HamcrestDemoTest {
@Test
@DisplayName("String Examples")
void stringExamples() {
String s1 = "Hello";
String s2 = "Hello";
assertThat("Comparing Strings", s1, is(s2));
assertThat(s1, equalTo(s2));
assertThat("ABCDE", containsString("BC"));
assertThat("ABCDE", not(containsString("EF")));
}
@Test
@DisplayName("List Examples")
void listExamples() {
// Create an empty list
List<String> list = new ArrayList();
assertThat(list, isA(List.class));
assertThat(list, empty());
// Add a couple items
list.add("One");
list.add("Two");
assertThat(list, not(empty()));
assertThat(list, hasSize(2));
assertThat(list, contains("One", "Two"));
assertThat(list, containsInAnyOrder("Two", "One"));
assertThat(list, hasItem("Two"));
}
@Test
@DisplayName("Number Examples")
void numberExamples() {
assertThat(5, lessThan(10));
assertThat(5, lessThanOrEqualTo(5));
assertThat(5.01, closeTo(5.0, 0.01));
}
}
One thing I like about Hamcrest is that it is very easy to read. For example, “assert that name is Steve
,” “assert that list has size 2
,” and “assert that list has item Two
” all read like regular sentences in the English language. In Listing 1, the stringExamples
test first compares two String
s for equality and then checks for substrings using the containsString()
method. An optional first argument to assertThat()
is the “reason” for the test, which is the same as the message in a JUnit assertion and will be displayed if the test fails. For example, if we added the following test, we would see the assertion error below it:
assertThat("Comparing Strings", s1, is("Goodbye"));
java.lang.AssertionError: Comparing Strings
Expected: is "Goodbye"
but: was "Hello"
Also note that we can combine the not()
logical method with a condition to verify that a condition is not true. In Listing 1, we check that the ABCDE String
does not contain substring EF
using the not()
method combined with containsString()
.