如果它们的差异小于1秒,如何使用specs2断言Date等于另一个Date?

时间:2014-08-22 07:24:26

标签: scala unit-testing specs2

我正在编写specs2测试,需要比较两个日期:

import java.util.Date

val date1: Date = getDate1();
val date2: Date = getDate2();

date1 must beEqualToAnotherDate(date2, 1.second)

没有这样的beEqualToAnotherDate匹配器,我怎么能在specs2中有效地做同样的事情呢?

2 个答案:

答案 0 :(得分:3)

您可以使用必须在之间:

val millis = date2.getTime()

date1.getTime() must beBetween(millis - 500, millis + 500)

答案 1 :(得分:3)

如果您想要自定义匹配器,可以尝试以下方法:

import java.util.Date

import org.specs2.matcher.{
  Expectable,
  Matcher,
  MatchResult,
  MatchersImplicits,
  Specification
}

object MySpecs extends Specification with MatchersImplicits {

  def beCloseInTimeTo(date: Date, timeDiff: Int) = new Matcher[Date] {
    def apply[D <: Date](e: Expectable[D]) = 
      result((e.value.getTime - date.getTime) < timeDiff,
        "Dates are nearly at the same time",
        "Dates are different",
        e)
  }

  dateA must beCloseInTimeTo(dateB, timeInMillis)
}