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

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?


  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

  2. Grand Casino Hinckley is house SM카지노 to 26 Blackjack tables including four-deck, and six-deck tables with limits from $10 a lot as} $3,000. When you play with your Grand Rewards card, you earn factors and cash again on blackjack. Bought this for a Field Problem and wasn’t disappointed. It matches, shapes and feels 100% better than any of the opposite rucks I’ve either been issued or bought.


Post a Comment

Comment, motherf*cker

Popular Posts