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

前端 未结 3 957
鱼传尺愫
鱼传尺愫 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:19

    you could just use good old-fashioned OO principles, e.g.

      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
        }  
      }
    

    Your code should get a reference to an implementation of TimeService via dependency injection. In resources.groovy use the MockTimeService only when running the tests

    import grails.util.Environment
    
    beans = {    
        if (Environment.current == Environment.TEST) {
            timeService(MockTimeService)
    
        } else {
             timeService(JodaTimeService)
        }
    }
    

提交回复
热议问题