Posted In: Hamcrest, Junit, Testing

How to unit test a date – JUnit + Hamcrest

Usecase – You need to unit test Date output and write multiple scenarios to test the data. Hamcrest library may be useful to achieve that

Hamcrest Date Matchers

Hamcrest 1.3

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

Classes used from Hamcrest

import org.hamcrest.number.OrderingComparison;

Using ErrorCollector so that execution continues even if assert statement fails.

package com.example.testing.hamcrest;

import static org.hamcrest.CoreMatchers.is;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.hamcrest.number.OrderingComparison;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;

public class TestHamcrestCollection4 {

	@Rule
	public ErrorCollector collector = new ErrorCollector();

	@Test
	public void testDateEquality() {

		try {
			// current date1
			Date currentDate1 = new SimpleDateFormat("yyyy-MM-dd")
			        .parse("2017-08-13");

			// current date2
			Date currentDate2 = new SimpleDateFormat("yyyy-MM-dd")
			        .parse("2017-08-13");

			// date before 5 days
			Date fiveDaysBefore = new SimpleDateFormat("yyyy-MM-dd")
			        .parse("2017-08-08");

			// date before 10 days
			Date tenDaysBefore = new SimpleDateFormat("yyyy-MM-dd")
			        .parse("2017-08-03");

			// positive - equality
			collector.checkThat(currentDate1, is(currentDate2));

			// positive - equality
			collector.checkThat(currentDate1,
			        OrderingComparison.greaterThanOrEqualTo(currentDate2));

			// positive - equality
			collector.checkThat(currentDate1,
			        OrderingComparison.comparesEqualTo(currentDate2));

			// positive - greaterThan
			collector.checkThat(currentDate1,
			        OrderingComparison.greaterThan(tenDaysBefore));

			// positive - greaterThan
			collector.checkThat(tenDaysBefore,
			        OrderingComparison.lessThan(fiveDaysBefore));

			// negative - greaterThan
			collector.checkThat(fiveDaysBefore,
			        OrderingComparison.lessThan(tenDaysBefore));

		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

Output

java.lang.AssertionError: 
Expected: a value less than <Thu Aug 03 00:00:00 IST 2017>
     but: <Tue Aug 08 00:00:00 IST 2017> was greater than <Thu Aug 03 00:00:00 IST 2017>
	at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
	at org.junit.Assert.assertThat(Assert.java:956)
	at org.junit.rules.ErrorCollector$1.call(ErrorCollector.java:65)

Tags: ,

by , on August 13th, 2017

  • Categories