Loading...

Works with JUnit 4

Base

  • anything
  • describedAs
  • is

Logic

  • allOf
  • anyOf
  • not

Object

  • equalTo
  • instanceOf
  • notNullValue, nullValue
  • sameInstance

Collections

  • hasEntry, hasKey, hasValue
  • hasItem
  • hasItemInArray

Number

  • closeTo
  • greaterThan, lessThan
  • greaterThanOrEqualTo, lessThanOrEqualTo

Text

  • equalToIgnoringCase
  • equalToIgnoringWhiteSpace
  • containsString, endsWith, startsWith

Java Docs

  • http://hamcrest.org/JavaHamcrest/javadoc/1.3/overview-summary.html

Maven

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

Collection Matchers

Check Collection Size

Example object with Lombok

package net.cinhtau.data;

import java.util.Map;

import lombok.Getter;
import lombok.Setter;

public class Configuration {
    /**
     * The elasticsearch host to connect with, IP address is also ok
     */
    @Getter @Setter
    private String host;
    /**
     * The http port to use
     */
    @Getter @Setter
    private int port;
    /**
     * Contains authentication data, only needed if elasticsearch is secured
     * either with x-pack or nginx basic auth
     */
    @Getter @Setter
    private Map<String, String> auth;
}

Example: Data structure is a Map, convert the values to a List (Collection)

import static org.hamcrest.collection.IsCollectionWithSize.hasSize;

@Test
public void readConfiguration() throws Exception {
    Configuration actual = ConnectionHelper.readConfiguration("config.yml");
        assertThat("authentication is not empty", new ArrayList<>(actual.getAuth().values()), hasSize(2));
}

Check Map value

import static org.hamcrest.collection.IsMapContaining.hasEntry;

@Test
public void readConfiguration() throws Exception {
    Configuration actual = ConnectionHelper.readConfiguration("config.yml");
    assertThat("user is elastic", actual.getAuth(), hasEntry(equalTo("user"), equalTo("elastic")));
    assertThat("password is heart", actual.getAuth(), hasEntry(equalTo("password"), equalTo("heart")));
}