Scala 测试期间冻结时间,模拟单例对象

Scala 测试期间冻结时间,模拟单例对象,scala,playframework,mockito,specs2,Scala,Playframework,Mockito,Specs2,我试图在规范执行期间冻结时钟。类似于但适用于Scala/Play 2.4 它还与模拟单例对象有关,因为我希望能够为ZonedDateTime.now()指定返回值。我的建议是始终将提供now方法的接口注入任何需要知道当前时间的方法。然后,您可以使用Mockito和specs2 mock精确返回您想要的时间 import org.specs2._, mock._ class TimeSpec extends Specification with Mockito { def is = s2"""

我试图在规范执行期间冻结时钟。类似于但适用于Scala/Play 2.4


它还与模拟单例对象有关,因为我希望能够为
ZonedDateTime.now()

指定返回值。我的建议是始终将提供
now
方法的接口注入任何需要知道当前时间的方法。然后,您可以使用Mockito和
specs2 mock
精确返回您想要的时间

import org.specs2._, mock._

class TimeSpec extends Specification with Mockito { def is = s2"""

    test with event creation some specific time $time1

  """

  def time1 = {
    val time = mock[DateTime]
    val timestamp = new DateTime("2016-01-30 12:00:00")  
    time.now returns timestamp

    val event = Event.create(time)
    event.dt === timestamp
  }
}

trait Time {
  def now: DateTime
}

case class Event(dt: DateTime)

object Event {
  def create(time: DateTime): Event = 
    Event(time.now)
}

你能举一个你想测试的例子吗。您可能只是需要一种不同的方法来编写或测试类。