Hamcrest Matchers: Complete Reference Guide for Java Testing
Hamcrest is a framework of matcher objects for writing test assertions in Java. Instead of assertEquals(expected, actual), you write assertThat(actual, equalTo(expected)). The matcher approach enables composable assertions and much better failure messages.
Hamcrest ships with JUnit 4 and is available as a standalone dependency. Understanding its matcher library is useful even if you use AssertJ or Selenide, because Mockito's argument matchers (when(mock.method(anyString()))) are built on Hamcrest's concept.
Setup
Hamcrest is bundled with JUnit 4. For standalone use or JUnit 5:
Maven
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>Gradle
testImplementation 'org.hamcrest:hamcrest:2.2'Static imports for readability:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;Core Matchers
Equality and Identity
assertThat(actual, equalTo(42));
assertThat(actual, not(equalTo(0)));
assertThat(actual, is(42)); // syntactic sugar for equalTo
assertThat(actual, is(not(0)));
// Reference equality
assertThat(actual, sameInstance(expected));
assertThat(actual, not(sameInstance(other)));
// Null checks
assertThat(result, notNullValue());
assertThat(result, nullValue());
assertThat(result, is(notNullValue()));Type Checking
assertThat(obj, instanceOf(String.class));
assertThat(obj, isA(String.class)); // alias for instanceOf
assertThat(obj, not(instanceOf(Integer.class)));Anything
assertThat(anything, anything()); // always passes
assertThat(anything, anything("description"));String Matchers
assertThat("Hello World", containsString("World"));
assertThat("Hello World", startsWith("Hello"));
assertThat("Hello World", endsWith("World"));
assertThat("Hello World", equalToIgnoringCase("hello world"));
assertThat(" hello ", equalToIgnoringWhiteSpace("hello"));
// Pattern
assertThat("user@example.com", matchesPattern(".*@.*\\..*"));
// Empty/blank
assertThat("", emptyString());
assertThat(" ", blankString());
assertThat("hello", not(emptyOrNullString()));Number Matchers
assertThat(42, greaterThan(10));
assertThat(42, greaterThanOrEqualTo(42));
assertThat(42, lessThan(100));
assertThat(42, lessThanOrEqualTo(42));
assertThat(42, between(10, 50)); // inclusive
// Close to (for floating point)
assertThat(3.14, closeTo(Math.PI, 0.01));
assertThat(0.1 + 0.2, closeTo(0.3, 0.0001));
// NaN and infinity
assertThat(Double.NaN, notANumber());Collection Matchers
Lists and Arrays
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
// Size
assertThat(numbers, hasSize(5));
assertThat(numbers, hasSize(greaterThan(3)));
// Contents
assertThat(numbers, hasItem(3));
assertThat(numbers, hasItems(1, 3, 5)); // contains all (any order)
assertThat(numbers, not(hasItem(99)));
// Exact match (order matters)
assertThat(numbers, contains(1, 2, 3, 4, 5));
// Exact match (any order)
assertThat(numbers, containsInAnyOrder(5, 3, 1, 4, 2));
// Every element matches
assertThat(numbers, everyItem(greaterThan(0)));
assertThat(numbers, everyItem(lessThan(10)));
// Empty
assertThat(List.of(), empty());
assertThat(numbers, not(empty()));Arrays
Integer[] arr = {1, 2, 3};
assertThat(arr, arrayWithSize(3));
assertThat(arr, arrayContaining(1, 2, 3));
assertThat(arr, arrayContainingInAnyOrder(3, 1, 2));
assertThat(arr, hasItemInArray(2));Maps
Map<String, Integer> scores = Map.of("Alice", 95, "Bob", 87);
assertThat(scores, hasKey("Alice"));
assertThat(scores, hasValue(95));
assertThat(scores, hasEntry("Bob", 87));
assertThat(scores, hasEntry(equalTo("Alice"), greaterThan(90)));
assertThat(scores, aMapWithSize(2));Combining Matchers
Hamcrest's power is in composition:
// Both conditions must match
assertThat(value, allOf(greaterThan(0), lessThan(100)));
assertThat(name, allOf(startsWith("J"), endsWith("n")));
// Either condition
assertThat(status, anyOf(equalTo("active"), equalTo("pending")));
// Negation
assertThat(value, not(equalTo(0)));
assertThat(list, not(empty()));
// Complex composition
assertThat(users,
hasItem(
allOf(
hasProperty("name", equalTo("Alice")),
hasProperty("age", greaterThan(18))
)
)
);Bean / Object Property Matchers
User user = new User("John", 30, "john@example.com");
assertThat(user, hasProperty("name", equalTo("John")));
assertThat(user, hasProperty("age", greaterThanOrEqualTo(18)));
assertThat(user, hasProperty("email", containsString("@")));
// Multiple properties
assertThat(user, allOf(
hasProperty("name", not(emptyString())),
hasProperty("age", greaterThan(0)),
hasProperty("email", containsString("@"))
));Custom Matchers
Extend TypeSafeMatcher<T> for reusable domain-specific matchers:
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
public class ValidEmailMatcher extends TypeSafeMatcher<String> {
@Override
protected boolean matchesSafely(String email) {
return email != null && email.matches("^[^@]+@[^@]+\\.[^@]+$");
}
@Override
public void describeTo(Description description) {
description.appendText("a valid email address");
}
@Override
protected void describeMismatchSafely(String email, Description description) {
description.appendText("was ").appendValue(email)
.appendText(" which is not a valid email");
}
public static ValidEmailMatcher validEmail() {
return new ValidEmailMatcher();
}
}Usage:
import static com.example.ValidEmailMatcher.validEmail;
assertThat("user@example.com", validEmail());
assertThat("not-an-email", not(validEmail()));Failure message: Expected: a valid email address but: was "not-an-email" which is not a valid email
Hamcrest with Mockito
Mockito's argument matchers are Hamcrest-compatible:
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
// Use Hamcrest matchers as Mockito argument matchers
verify(emailService).send(argThat(validEmail()));
verify(userService).findByAge(argThat(greaterThan(18)));
when(repo.findAllByStatus(argThat(anyOf(equalTo("active"), equalTo("pending")))))
.thenReturn(mockUsers);Hamcrest vs JUnit 5 Built-in Assertions
JUnit 5's built-in assertions (assertEquals, assertTrue, etc.) are fine for simple cases. Hamcrest adds value when:
- You need composable conditions (
allOf,anyOf) - You want descriptive failure messages (
describeTo) - You need custom matchers you can reuse across tests
- You're using Mockito and want consistent matcher vocabulary
For most projects, either use Hamcrest consistently or switch to AssertJ (which has a more Java-idiomatic fluent API). Mixing both in the same codebase creates cognitive overhead.