Search code examples
scalaunit-testingspecs2

How to use specs2 to assert a Date is equal to another Date if their difference is less than 1 second?


I'm writing a specs2 test, and need to compare two dates:

import java.util.Date

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

date1 must beEqualToAnotherDate(date2, 1.second)

There is no such beEqualToAnotherDate matcher, how can I do the same in specs2 efficiently?


Solution

  • If you want a custom matcher, you can try something like:

    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)
    }