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

Stu*_*att 8 time grails groovy mocking jodatime

我正在编写一些代码来执行与当前时间相关的日期和时间计算.在Joda时间,这是通过(Java)构造函数访问的,因为它是一个不可变对象.我需要能够模拟,以便new DateTime()返回一个特定的常量瞬间,这样我就可以做出明智的测试断言,但只留下所有其他DateTime方法.

这证明是令人讨厌的.Grails mockFor(DateTime, true)不会让我模拟Java构造函数,但是没有明显或可读的非构造方法来获取Joda时间.

唯一可用的选项似乎涉及低级JVM技术,如JMockit或EasyMock 3类模拟,这是Grails的痛苦.有没有简单/直接的方法来实现这一目标?

alp*_*ian 18

我知道这已经被接受了,但是在Joda-time你可以冻结并将它设置为你喜欢的任何东西.所以你可以冻结时间,提前时间,及时倒退.只要你一直使用Joda,你的对象就会"现在",无论你设置的是什么时候.

// 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();
Run Code Online (Sandbox Code Playgroud)


Vic*_*nko 5

我们最终dateServicenow()方法创建了.在单元测试中,我们用它来模拟它

domainInstance.dateService = [ now: { currentTime } ] as DateService
Run Code Online (Sandbox Code Playgroud)

currentTime单元测试类字段在哪里.这强加了每个人对dateService(我们唯一的近全局依赖)的依赖,对于src类,必须手动传递它.

单元测试,OTOH,看起来很清楚.