5

I have been looking around but I have not found anything useful. Are there any 3rd party libraries that work with hamcrest that have extensive date matching?

Specifically I am looking for matchers along the lines of:

assertThat(myDate, is(withinMinutes(sourceDate, 10)));
assertThat(myDate, is(afterDate(sourceDate)));
assertThat(myDate, is(betweenDates(startDate, endDate)));

I wanted to see if there was anything out there before I rolled my own.

Dan
  • 51
  • 3

2 Answers2

3

I've written a set of date matchers which look like what you're after. The source is here https://github.com/eXparity/hamcrest-date. An example of how to use the within matcher

assertThat(dateUnderTest, DateMatchers.within(2, TimeUnit.SECONDS, new Date()));

You can add it with maven adding this to your pom.xml

<dependency>
    <groupId>org.exparity</groupId>
    <artifactId>hamcrest-date</artifactId>
    <version>2.0.1</version>
</dependency>
borjab
  • 11,149
  • 6
  • 71
  • 98
stewbis
  • 370
  • 3
  • 10
  • I think what you're linking here is actually what the poster is after, but to avoid the perception of self promotion it's a good idea to provide some examples in the answer of how this would work. – EdC Sep 16 '12 at 10:05
  • Thanks for the heads-up, i've added an example – stewbis Sep 16 '12 at 11:40
0

You should try fest-assert, it is not compliant with hamcrest but IMHO it is superior to it ("more fluent"). For example with date :

@Test
public void is_between_date_assertions_examples() {

    // various usage of isBetween assertion,
    // Note that isBetween(2002-12-17, 2002-12-19) includes start date but end date :
    assertThat(theTwoTowers.getReleaseDate())
            // = 2002-12-18
            .isBetween(theFellowshipOfTheRing.getReleaseDate(), theReturnOfTheKing.getReleaseDate())
            .isBetween(parse("2002-12-17"), parse("2002-12-19")) // [2002-12-17, 2002-12-19[
            .isBetween("2002-12-17", "2002-12-19") // [2002-12-17, 2002-12-19[
            .isNotBetween("2002-12-17", "2002-12-18") // [2002-12-17, 2002-12-18[
            .isBetween("2002-12-17", "2002-12-18", true, true); // [2002-12-17, 2002-12-18]
}

The full example with date is here, the others are there.

gontard
  • 28,720
  • 11
  • 94
  • 117