Java Programming Tutorials

Java programming tutorials with many code examples!

JUnit Matchers CheatSheet

How to Hamcrest Matchers that come with JUnit? The following Matchers Cheatsheet shows all CoreMatchers in action to make unit tests readable.

Readability is very important property of unit tests. JUnit comes with a bunch of static methods that makes it easier to express assertions on tested objects. These static methods produce objects known as Matchers and are contained in org.hamcrest.CoreMatchers class.

JUnit Matchers Cheatsheet

package com.farenda.junit;

import org.junit.Test;

import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

public class MatchersCheatSheetTest {

    @Test
    public void checkValue() {
        assertThat(Math.abs(-42), is(42));
        assertThat(Math.abs(-42), is(equalTo(42)));
        assertThat("JUnit", equalTo("JUnit"));

        // this matches anything :-)
        assertThat("JUnit", anything());
    }

    @Test
    public void checkTypeOfObject() {
        String computedValue = "JUnit tutorial";
        // all are equivalent:
        assertThat(computedValue, instanceOf(String.class));
        assertThat(computedValue, is(instanceOf(String.class)));
        assertThat(computedValue, isA(String.class));
        assertThat(computedValue, any(String.class));
    }

    @Test
    public void checkIdentity() {
        List<Integer> numbers = asList(1, 2, 3);
        // check that object is the same instance (all are equivalent):
        assertThat(numbers, sameInstance(numbers));
        assertThat(numbers, is(sameInstance(numbers)));
        assertThat(numbers, theInstance(numbers));
        assertThat(numbers, is(theInstance(numbers)));
    }

    @Test
    public void checkWhatObjectIsNot() {
        String answer = "42";
        assertThat(1, not(answer));
        assertThat("abc", is(not(answer)));
        assertThat(answer, is(not(instanceOf(List.class))));
    }

    @Test
    public void checkNotNull() {
        // both are the same:
        assertThat("Hamcrest", notNullValue());
        assertThat("Matchers", not(nullValue()));
    }

    @Test
    public void checksOnStrings() {
        assertThat("JUnit tutorial", containsString("tut"));
        assertThat("Esperanto", startsWith("E"));
        assertThat("Esperanto", endsWith("o"));
    }

    @Test
    public void checkCollections() {
        assertThat(asList("JUnit", "Tutorial"),
                everyItem(containsString("t")));

        List<Integer> numbers = asList(1, 2, 3);
        assertThat(numbers, hasItem(equalTo(1)));
        assertThat(numbers, hasItems(equalTo(3), isA(Number.class)));
    }

    @Test
    public void descriptiveError() {
        int expected = 42;
        assertThat(1, describedAs("The number suppose to be %0",
                equalTo(expected),
                expected));
    }

    @Test
    public void combiningMatchers() {
        assertThat("Esperanto", both(startsWith("E"))
                .and(endsWith("o")));

        assertThat("JUnit", either(startsWith("a"))
                .or(endsWith("z"))
                .or(containsString("Tutorial"))
                .or(anything()));

        assertThat("JUnit", allOf(
                containsString("Unit"),
                startsWith("J"),
                endsWith("it")));

        assertThat(asList(1, 2, 3), anyOf(
                hasItem(2),
                instanceOf(Number.class)));
    }
}

How pros do it

The following test from Spring Framework shows how CoreMatchers.anyOf can be used in practice:

package org.springframework.context.support;

import org.junit.Test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

/**
 * Tests covering the integration of the {@link Environment} into
 * {@link ApplicationContext} hierarchies.
 *
 * @author Chris Beams
 * @see org.springframework.core.env.EnvironmentSystemIntegrationTests
 */
public class EnvironmentIntegrationTests {

      @Test
      public void repro() {
              ConfigurableApplicationContext parent = new GenericApplicationContext();
              parent.refresh();

              AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
              child.setParent(parent);
              child.refresh();

              ConfigurableEnvironment env = child.getBean(ConfigurableEnvironment.class);
              assertThat("unknown env", env, anyOf(
                              sameInstance(parent.getEnvironment()),
                              sameInstance(child.getEnvironment())));
              assertThat("expected child ctx env", env, sameInstance(child.getEnvironment()));

              child.close();
              parent.close();
      }

}
Share with the World!