在Grails中,有没有一种好的方法可以使用Joda time模拟当前时间?

| 我正在编写一些代码,根据当前时间进行日期和时间计算。在Joda时代,这是通过(Java)构造函数访问的,因为它是不可变的对象。我需要能够模拟,以便ѭ0返回一个特定的常量瞬间,这样我就可以进行明智的测试断言,但不要理会所有其他DateTime方法。 事实证明这很讨厌。 Grails的“ 1”不允许我模拟Java构造函数,但是没有明显或可读的非构造方法来获取Joda时间。 唯一可用的选项似乎涉及低级JVM技术,例如JMockit或EasyMock 3类模拟,这是Grails的苦恼。有没有简单/直接的方法来实现这一目标?     
已邀请:
我们最终使用
now()
方法创建了
dateService
。在单元测试中,我们使用
domainInstance.dateService = [ now: { currentTime } ] as DateService
其中“ 5”是单元测试类别字段。这强加了每个人对ѭ2dependency的依赖(我们只有近乎全局的依赖),而对于
src
类,则必须手动传递它。 OTOH,单元测试看起来很清楚。     
我知道这已经被接受,但是使用Joda-time可以冻结并将其设置为您喜欢的任何值。因此,您可以冻结时间,提前时间,倒退时间。如果您一直使用Joda,则无论您将其设置为什么时间,您的对象都将获得“ now”。
// Stop time (and set a particular point in time):
DateTimeUtils.setCurrentMillisFixed(whenever);

// Advance time by the offset:
DateTimeUtils.setCurrentMillisOffset(offsetFromCurrent);

// Restore time (you could do this in an @After method)
DateTimeUtils.setCurrentMillisSystem();
    
您可以使用良好的老式OO原则,例如
  interface TimeService {
    DateTime getCurrentTime()

    // other time-related methods
  }

  class JodaTimeService implements TimeService {
    DateTime getCurrentTime() {
      new DateTime()
    }  
  }

  class MockTimeService implements TimeService {
    DateTime getCurrentTime() {
      // return a fixed point in time
    }  
  }
您的代码应通过依赖注入获得ѭ10的实现的引用。在ѭ11中,仅在运行测试时才使用ѭ12
import grails.util.Environment

beans = {    
    if (Environment.current == Environment.TEST) {
        timeService(MockTimeService)

    } else {
         timeService(JodaTimeService)
    }
}
    

要回复问题请先登录注册