In Grails, is there a good way to mock the current time using Joda time?

前端 未结 3 974
鱼传尺愫
鱼传尺愫 2020-12-30 09:50

I\'m writing some code that does date and time calculations against the current time. In Joda time, this is accessed through a (Java) constructor, as it is an immutable obje

3条回答
  •  天涯浪人
    2020-12-30 10:30

    I know this as already been accepted, but with Joda-time you can freeze and set it to be whatever you like. So you can freeze time, advance time, go backwards in time. Provided you're using Joda consistently, your objects will get "now" as whatever time you've set that to be.

    // 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();
    

提交回复
热议问题