Java Hamcrest Documentation

repository·master·Indexed 25 days ago

https://github.com/hamcrest/javahamcrest

A 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.

Tokens
3.3K
Snippets
9
Records
18
Agent score
81%

What's inside Java Hamcrest

  1. Explore Hamcrest related projects and extensions

    master

    If 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 using jsonEquals and jsonPartEquals.
      • 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 comparing javax.mail package 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: Includes CollectionMatchers, MapMatchers, FieldMatcher, and SerializableMatcher.
      • 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.
  2. Improve readability with 'Sugar' matchers

    master

    The is matcher 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));
  3. Understand Hamcrest Jar packaging changes

    master

    Hamcrest 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 between hamcrest-core.jar and hamcrest-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; use hamcrest.jar instead).
  4. Install Java Hamcrest via Maven or Gradle

    master
    Java 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 your pom.xml (Maven) or build.gradle (Gradle) files. For specific dependency coordinates and distribution details, refer to the Hamcrest Distributables documentation.
  5. Build Java Hamcrest from source

    master

    To 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/libs directory.

    ./gradlew clean build javadoc
  6. Write your first Hamcrest test with assertThat

    master

    To use Hamcrest for assertions, use the assertThat method from MatcherAssert. 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.assertThat and org.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)); 
      } 
    } 
  7. Download Java Hamcrest and configure dependencies

    master
    Java 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.
  8. Create a custom matcher by extending TypeSafeMatcher

    master

    To create a custom matcher, the most convenient approach is to extend TypeSafeMatcher<T>. This handles type casting for you. You must implement two methods:

    1. matchesSafely(T item): Contains the actual logic to determine if the item matches.
    2. 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(); 
      } 
    
    }
  9. Add Hamcrest to a Maven Project

    master

    To use the latest Hamcrest (version 3.0) in a Maven project, add the following dependency to your pom.xml. It is recommended to use the test scope.

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest</artifactId>
        <version>3.0</version>
        <scope>test</scope>
    </dependency>