Search code examples
scalascalatestnanotimejava.time.instant

ScalaTest: treat Instants as equal when in the same millisecond


I have a case class that I serialize to JSON, and a test case that checks that round-tripping works.

Buried deep inside the case class are java.time.Instants, which I put into JSON as their epoch milliseconds.

Turns out that an Instant actually has nanosecond precision and that gets lost in translation, making the test fail because the timestamps are slightly off now.

Is there an easy way to make Scalatest ignore the difference? I just want to fix the test, the loss in precision is totally acceptable for the application.


Solution

  • We use Clock.instant to know the current time instead of Instant.now to avoid this problem. So the code for the class should be this way

    class MyClass(clock: Clock) {
      def getResult(): Result = {
        Result(clock.instant)
      }
    }
    

    and at the test, we mock clock.instant to guarantee we check the exact same time.

    class MyClassTest {
      val customTime = Instant.now
      val clock = mock[Clock]
      clock.instant() returns customTime
    
      // test
      val myClass = new MyClass(clock)
      val expectedResult = Result(customTime)
      myClass.getResult ==== expectedResult
    }