Core Java

Verifying DateTime and Date with Hamcrest

Since I started diving into automated testing and practicing TDD, verification of date values was pain. Luckily there is nice library for legacy Date and new Java 8 DateTime APIs, which cures this pain.

If you belong to healthier part of Java development community and practicing unit testing on daily basis, you probably are aware of Hamcrest Java library. It can make your tests much more readable. It’s architecture is very modular and is used by various other testing libraries.

Major part of it’s flexibility is it concept of Matcher. I am not going to dive into this concept now. If you are not familiar, just take a quick look at Hamcrest tutorial. One of the matcher you can plug into your testing toolbox is library hamcrest-date. With this library we can easily test that date was generated within certain range:

@Test
public void validateDate() {
    //GIVEN
    Date expectedDate = new Date();
 
    //WHEN
    Date actualDate = new Date();
 
    //THEN
    assertThat(actualDate, DateMatchers.within(2, ChronoUnit.SECONDS, expectedDate));
}

We can do that also for Java 8 types:

@Test
public void validateDateTime() {
    //GIVEN
    LocalDateTime expectedDateTime = LocalDateTime.now();
 
    //WHEN
    LocalDateTime actualDateTime = LocalDateTime.now();
 
    //THEN
    assertThat(actualDateTime, LocalDateTimeMatchers.within(2, ChronoUnit.SECONDS, expectedDateTime));
}

Or pick various exotic verifications hamcrest-core library provides:

@Test
public void validateZonedDateTime() {
    //GIVEN
    ZonedDateTime expectedDateTime = ZonedDateTime.of(2016, 3, 20, 13, 3, 0, 0, ZoneId.of("GMT+1"));
 
    //WHEN
    ZonedDateTime actualDateTime = ZonedDateTime.of(2016, 3, 20, 13, 3, 0, 0, ZoneId.of("GMT-0"));
 
    //THEN
    assertThat(actualDateTime, ZonedDateTimeMatchers.sameDay(expectedDateTime));
    assertThat(actualDateTime, ZonedDateTimeMatchers.after(expectedDateTime));
    assertThat(actualDateTime, ZonedDateTimeMatchers.isSunday());
    assertThat(actualDateTime, ZonedDateTimeMatchers.isMarch());
}

Lubos Krnac

Lubos is a Java/JavaScript developer/Tech Lead and Automation enthusiast. His religion is to constantly improve his developments skills and learn new approaches. He believes TDD drives better design and nicely decoupled code. Past experience includes C++, Assembler and C#.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button