2011-12-23 53 views
24

我需要在某個測試用例的日期之前/之後進行測試。如果可能,我想使用Hamcrest matchersHamcrest Date Matchers

Hamcrest(Java)有沒有與日期合作的匹配器?如果是這樣,我可以找到哪些包/類可以找到特定的日期匹配器功能?

回答

28

OrderingComparison::greaterThan匹配器將工作在任何類型可以比較自己(它在org.hamcrest.number包,但它並不實際數量具體)。日期是這樣一種類型。

+0

謝謝。看起來他們已經擺脫了這個班,轉而採用靜態工廠方法,這使得一個非常穩定的鏈接成爲不可能,但我已經儘可能地修復了它。 – 2013-09-28 20:57:12

+0

的確如此。還有一些擴展提供了一些更易於閱讀的方法。例如,[Cirneco](https://github.com/ozimov/cirneco)提供了匹配器'J7Matchers :: after',它是'OrderingComparison :: greaterThan'的別名。從我的觀點來看,_sematic_在單元測試中一直都很重要,這就是爲什麼我通常更喜歡Google Truth提供的無用方法,但有時我必須在傳統項目中處理Hamcrest。 – JeanValjean 2016-01-09 23:31:11

4

有一些hamcrest擴展可以減輕一些與日期有關的測試。請check here.

+0

哇,這些都是非常整潔。 – 2012-01-07 05:59:11

3

你可以看看將被添加到hamcrest新的日期匹配器(我不知道什麼時候想):

Date matchers discussion/code changes on github

快速瀏覽一下之後,似乎將有一個新的打包org.hamcrest.date含有:

  • IsAfter
  • IsBefore
  • IsSameDayOfTheMonth
  • IsSameDayOfTheWeek
  • IsSameDayOfTheYear
  • IsSameHour
  • IsSameInstant
  • IsSameMinute
  • IsSameMonth
  • IsSameSecond
  • IsSameYear
  • IsWithin
12

有由庫在https://github.com/eXparity/hamcrest-date提供hamcrest日期匹配器的庫,它也可用於行家,常春藤,等在

<dependency> 
    <groupId>org.exparity</groupId> 
    <artifactId>hamcrest-date</artifactId> 
    <version>1.1.0</version> 
</dependency> 

它支持各種匹配器的日期,以便允許構建體如

Date myBirthday = new Date(); 
MatcherAssert.assertThat(myBirthday, DateMatchers.after(Moments.today())); 

Date myBirthday = new Date(); 
MatcherAssert.assertThat(myBirthday, DateMatchers.isToday()); 
0

還有Cirneco extension。它具有若干Date特定匹配器(例如monday())以及由於實施Comparable而應用於日期的其他(例如參見between(),betweenInclusive())。該計劃還支持JDK7版本庫中的Joda Time以及JDK8版本中的新日期類(主要爲LocalDate)。

你可以做這樣的斷言:

final Date date = new Date(); 
assertThat(date, is(monday())); // JUnit style 
given(date).assertIs(monday()); // Cirneco style 

您可以使用下面的依賴提供符合規定的JDK7項目:

<dependency> 
    <groupId>it.ozimov</groupId> 
    <artifactId>java7-hamcrest-matchers</artifactId> 
    <version>0.7.0</version> 
</dependency> 

或以下,如果您使用JDK8

<dependency> 
    <groupId>it.ozimov</groupId> 
    <artifactId>java8-hamcrest-matchers</artifactId> 
    <version>0.7.0</version> 
</dependency> 
2

Matchers#greaterThan匹配器與Date s和其他Comparable對象。

這裏的方法來檢查你的日期是大於或等於(≥)一些預產期:

import static org.hamcrest.Matchers.equalTo; 
import static org.hamcrest.Matchers.greaterThan; 
import static org.hamcrest.core.AnyOf.anyOf; 
... 

Date expectedMin = new Date() 
// Execute the method being tested 
Date resultDate = getDate(); 
// Validate 
assertThat(resultDate, anyOf(greaterThan(expectedMin), equalTo(expectedMin)))