I'd like to test if a java.time.LocalDate is within a fixed number of days of a test date and I'd like to use Hamcrest matchers if possible. Are there any matchers for Hamcrest (java) for working with Dates?
There is a date matcher extension library for hamcrest, hamcrest-date, which can match LocalDate, LocalDateTime, ZoneDateTime, and Date. To compare if a LocalDate is within a number of days of a test date you can use this syntax:
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import org.exparity.hamcrest.date.LocalDateMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
public class LocalDateTest {
@Test
public void isDate() {
LocalDate actual = LocalDate.now();
LocalDate expected = LocalDate.of(2015, Month.OCTOBER, 15);
MatcherAssert.assertThat(actual,
LocalDateMatchers.within(5, ChronoUnit.DAYS, expected));
}
}
The library can be included in you by adding this dependency to your pom.
<dependency>
<groupId>org.exparity</groupId>
<artifactId>hamcrest-date</artifactId>
<version>2.0.1</version>
</dependency>
The project is hosted on github at https://github.com/eXparity/hamcrest-date
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With