The Easy Way: Mocking time in Groovy

If you have time-dependent software, you usually want to mock time for unit testing. There are frameworks for this (e.g. JMockIt), but I think Groovy makes it easy enough to do it without any framework.

The idea is to use MetaClass to replace Calendar.getInstance() method. The problem with this approach is that we still need the original method or we can't create new Calendar instances. But Groovy makes it easy:

private static MetaMethod oldCalendarGetInstance = null 
 
/**
 * Mocks time to the time specified by Calendar parameter instance.
 * Time is frozen on the time specified in this 
 * Calendar instance.
 * @param mockCalendar Calendar with mocked time 
 */
@Synchronized 
static void mockAndFreezeTime(final Calendar mockCalendar) {
    if (!oldCalendarGetInstance) {
        oldCalendarGetInstance = Calendar.metaClass.getStaticMetaMethod('getInstance',
                                     [] as Object[])
    }
    Calendar.metaClass.static.getInstance = {
        def calendar = oldCalendarGetInstance.invoke(Calendar, [] as Object[]) as Calendar
        calendar.time = mockCalendar.time
        calendar
    }
}

A quick explanation:
  • oldCalendarGetInstance is where we are going to store the original Calendar.getInstance() method.
  • @Synchronized is a Groovy AST that implements synchronization correctly (the right way, unlike Java's synchronized).
  • We store the original method if we haven't replaced it yet.
  • Calendar.metaClass.static.getInstance accesses Calendar.getInstance method using Groovy's MetaClass functionality.
  • We just assign the method to our new implementation using a closure.
Yes, that's it. After calling this method, next time we call Calendar.getInstance() from anywhere in our code, it will go through our implementation. Cool, huh?

Comments

  1. The Easy Way: Mocking Time In Groovy >>>>> Download Now

    >>>>> Download Full

    The Easy Way: Mocking Time In Groovy >>>>> Download LINK

    >>>>> Download Now

    The Easy Way: Mocking Time In Groovy >>>>> Download Full

    >>>>> Download LINK T8

    ReplyDelete

Post a Comment

Comment, motherf*cker

Popular Posts