【问题标题】:Hamcrest Matchers for Java 8 LocalDate [closed]用于 Java 8 LocalDate 的 Hamcrest 匹配器 [关闭]
【发布时间】:2015-10-15 16:14:27
【问题描述】:

我想测试 java.time.LocalDate 是否在测试日期的固定天数内,如果可能的话,我想使用 Hamcrest 匹配器。 Hamcrest (java) 是否有任何匹配器用于处理日期?

【问题讨论】:

    标签: java unit-testing hamcrest


    【解决方案1】:

    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上https://github.com/eXparity/hamcrest-date

    【讨论】:

    • 你能把你的代码合并到hamcrest吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    相关资源
    最近更新 更多