用于Java 8 LocalDate的Hamcrest Matchers

ste*_*bis 4 java unit-testing hamcrest

我想测试java.time.LocalDate是否在测试日期的固定天数内,如果可能的话我想使用Hamcrest匹配器.Hamcrest(java)是否有与Dates合作的匹配器?

ste*_*bis 10

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));
  }
}
Run Code Online (Sandbox Code Playgroud)

通过将此依赖项添加到您的pom,可以将库包含在您的脑中.

<dependency>
  <groupId>org.exparity</groupId>
  <artifactId>hamcrest-date</artifactId>
  <version>2.0.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

该项目在github上托管,网址https://github.com/eXparity/hamcrest-date