Java Hamcrest Documentation
repository·master·Indexed 25 days ago
https://github.com/hamcrest/javahamcrestA library of matchers for creating flexible, readable, and expressive assertions in tests. It provides a wide variety of built-in matchers for core logic, objects, beans, collections, numbers, and text, as well as the ability to create custom matchers by extending TypeSafeMatcher. The documentation covers installation via Maven and Gradle, upgrading from version 1.x to 3.0, and usage of the assertThat method.
What's inside Java Hamcrest
- Hamcrest is a library of matchers designed to be combined into flexible expressions of intent within tests. Beyond testing, these matchers can be used for other logic-based purposes.
Explore Hamcrest related projects and extensions
masterIf the core Java Hamcrest library does not provide the specific matchers you need, several community projects offer specialized extensions for different data types and testing scenarios:
Specialized Matchers by Domain
- JSON & Data Formats:
hamcrest-json: For comparing entire JSON documents.JsonUnit: For comparing JSON structures usingjsonEqualsandjsonPartEquals.json-path-matchers: For evaluating JSON path expressions.hamcrest-java-extras: Provides JSON matchers.Hamcrest HAR: For HTTP archive files.
- Web & Networking:
http-matchers: To test web services via the JAX-RS API.Hamcrest Mail: For comparingjavax.mailpackage types.
- Database & Querying:
Hamcrest Querydsl: For checking query results (e.g.,hasResultSize,hasColumnRange,hasColumnMax,hasColumnMin,hasColumnContainingAll,hasColumnContainingAny).Hamcrest Result Set Matcher: For comparing JDBC result sets.
- Java Objects & POJOs:
Hamcrest 1.3 Utility Matchers: IncludesCollectionMatchers,MapMatchers,FieldMatcher, andSerializableMatcher.Hamcrest auto matcher: Uses reflection to automatically match model classes.Hamcrest Composites: For comparing complex Java objects.Shazamcrest: Matchers for beans with custom field matching and improved failure messages.Spotify's hamcrest matchers: Matchers for POJOs, JSON, and Java 8 types.hamcrest-pojo-matcher-generator: An annotation processor to generate feature-matchers from POJOs.
- Filesystem & Dates:
Hamcrest Path: For testing path existence and permissions.Hamcrest Date: For comparing dates.
Asynchronous Testing & Polling
Awaitility: A DSL for expressing expectations of asynchronous systems.Proboscis: A library for polling for results in asynchronous systems.
- JSON & Data Formats:
Improve readability with 'Sugar' matchers
masterThe
ismatcher acts as a decorator that improves the readability of assertions without changing their logic. It can be used to wrap other matchers or even direct values.Equivalent assertions:
assertThat(theBiscuit, equalTo(myBiscuit)); assertThat(theBiscuit, is(equalTo(myBiscuit))); assertThat(theBiscuit, is(myBiscuit));Understand Hamcrest Jar packaging changes
masterHamcrest has transitioned from multiple specialized jars to a single unified jar.
Current Version (2.x and 3.0):
hamcrest.jar: Contains all base classes and standard matcher implementations (previously split betweenhamcrest-core.jarandhamcrest-library.jar).
Legacy Versions (Prior to 2.x):
hamcrest-core.jar: Core API and foundation matchers.hamcrest-library.jar: Matcher implementations based on the core functionality.hamcrest-integration.jar: Integration with tools like jMock and EasyMock (no new releases since 1.3).hamcrest-generator.jar: Internal compile-time tool for generating matcher classes (no new releases since 1.3).hamcrest-all.jar: A single jar containing all classes from all other jars (no new releases since 1.3; usehamcrest.jarinstead).
Install Java Hamcrest via Maven or Gradle
masterJava Hamcrest can be added to your project using standard build tooling. You can obtain the binaries from Maven Central or by adding a dependency declaration to yourpom.xml(Maven) orbuild.gradle(Gradle) files. For specific dependency coordinates and distribution details, refer to the Hamcrest Distributables documentation.Build Java Hamcrest from source
masterTo build Hamcrest from source, you must have a minimum of JDK 1.8 installed. Use the included Gradle wrapper to perform a clean build and generate Javadocs. This process downloads the necessary Gradle version, runs all tests, and packages the compiled classes into a JAR file located in the
hamcrest/build/libsdirectory../gradlew clean build javadocGet started with Java Hamcrest
masterTo begin using Java Hamcrest, you can follow the official tutorial to learn how to combine matchers into flexible expressions of intent. For detailed technical specifications, refer to the JavaDoc API documentation.Write your first Hamcrest test with assertThat
masterTo use Hamcrest for assertions, use the
assertThatmethod fromMatcherAssert. This method takes the subject of the assertion as the first parameter and a matcher as the second. You can also provide an optional string identifier as the first parameter to provide better context in failure messages.To use the standard library of matchers, statically import
org.hamcrest.MatcherAssert.assertThatandorg.hamcrest.Matchers.*.import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class BiscuitTest { @Test public void testEquals() { Biscuit theBiscuit = new Biscuit("Ginger"); Biscuit myBiscuit = new Biscuit("Ginger"); assertThat(theBiscuit, equalTo(myBiscuit)); } }Download Java Hamcrest and configure dependencies
masterJava Hamcrest provides distributables and guidance on dependency configuration for various build tools. You can find the necessary files and setup instructions in the 'Distributables and Dependency Configuration' section of the documentation.Create a custom matcher by extending TypeSafeMatcher
masterTo create a custom matcher, the most convenient approach is to extend
TypeSafeMatcher<T>. This handles type casting for you. You must implement two methods:matchesSafely(T item): Contains the actual logic to determine if the item matches.describeTo(Description description): Defines the failure message used when the matcher fails.
Best Practice: Always ensure your custom matcher is stateless so that a single instance can be safely reused across multiple tests. It is common to provide a static factory method for easy use in tests.
package org.hamcrest.examples; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class IsNotANumber extends TypeSafeMatcher { @Override public boolean matchesSafely(Double number) { return number.isNaN(); } public void describeTo(Description description) { description.appendText("not a number"); } public static Matcher notANumber() { return new IsNotANumber(); } }Download the Hamcrest Jar directly
masterYou can download Hamcrest jars directly from Maven Central by searching for the groupId
org.hamcrestat the following link:Add Hamcrest to a Maven Project
masterTo use the latest Hamcrest (version 3.0) in a Maven project, add the following dependency to your
pom.xml. It is recommended to use thetestscope.<dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest</artifactId> <version>3.0</version> <scope>test</scope> </dependency>