JUnit – assertThat (Hamcrest) – part 1

Hamcrest is a framework for creating matcher objects. These matcher objects are predicates and are used to write rules which can be satisfied under certain conditions. They are most often used in testing. Hamcrest lets us step beyond simple JUnit asserts and enables us to craft very specific and readable verification code. Hamcrest has the target to make tests as readable as possible. In general, the Hamcrest error messages are also much easier to read. Using Hamcrest matchers also provides more type safety as these matchers uses generics.

Simple Matchers

  • any()
@Test
public void anyMatcherExample() {

    int age = 30;
    assertThat(age, is(any(Integer.class)));        
}
  • anything()
@Test
public void anythingMatcherExample() {

    Integer age = 30;
    assertThat(age, is(anything()));
}
  • arrayContaining()

Does the array contain all given items in the order in which they are input to the matcher?

@Test
public void arrayContainingMatcherExample() {

    String[] names = {"Jon", "Peter", "Paul"};
    assertThat(names, is(arrayContaining("Jon", "Peter", "Paul")));
}
  • arrayContainingInAnyOrder()

Does the array contain all the given items? Length of the array must match the number of matchers, but their order is not important.

@Test
public void arrayContainingInAnyOrderMatcherExample() {

    String[] names = {"Jon", "Peter", "Paul"};
    assertThat(names, is(arrayContainingInAnyOrder("Peter", "Paul", "Jon")));
}
  • arrayWithSize()

Does the input array have exactly the specified length?

@Test
public void arrayWithSizeMatcherExample() {

    String[] names = {"Jon", "Peter", "Paul"};
    assertThat(names, is(arrayWithSize(3)));
}
@Test
public void arrayWithSizeGreaterThanMatcherExample() {

    String[] names = {"Jon", "Peter", "Paul"};
    assertThat(names, is(arrayWithSize(greaterThan(2))));
}
  • closeTo()

Matcher which can be used with either Double or BigDecimal to check if a value is within a specified error margin of an expected value.

@Test
public void closeToDoubleMatcherExample() {

    Double temperature = 25.5;
    assertThat(temperature, closeTo(25.0, 0.5));
}
@Test
public void closeToBigDecimalMatcherExample() {

    BigDecimal totalValue = new BigDecimal(234.00);
    assertThat(totalValue, closeTo(new BigDecimal(230.0), new BigDecimal(5)));
}

 

 

 

 

2 thoughts on “JUnit – assertThat (Hamcrest) – part 1”

Leave a Reply