我想测试java.time.LocalDate是否在测试日期的固定天数内,并且如果可能的话我想使用Hamcrest匹配器。 Hamcrest(java)是否有与Dates合作的匹配器?
答案 0 :(得分:9)
hamcrest,hamcrest-date有一个日期匹配器扩展库,可以匹配LocalDate,LocalDateTime,ZoneDateTime和Date。要比较LocalDate是否在测试日期的天数内,您可以使用以下语法:
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));
}
}
通过将此依赖项添加到您的pom,可以将库包含在您的身上。
<dependency>
<groupId>org.exparity</groupId>
<artifactId>hamcrest-date</artifactId>
<version>2.0.1</version>
</dependency>
的github上托管