我正在编写specs2测试,需要比较两个日期:
import java.util.Date
val date1: Date = getDate1();
val date2: Date = getDate2();
date1 must beEqualToAnotherDate(date2, 1.second)
没有这样的beEqualToAnotherDate
匹配器,我怎么能在specs2中有效地做同样的事情呢?
答案 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)
}