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()); }
- Kudos to creator for this nice little library. This example is hosted in Github.
Reference: | Verifying DateTime and Date with Hamcrest from our JCG partner Lubos Krnac at the Lubos Krnac Java blog blog. |