Friday, 5 October 2012

Mockito stubs

So I was testing this bit of code that is time sensitive.

To test all of the conditions I needed to be able to simulate time passing in my test. The obvious thing to do was to create a facade for fetching the calendar (wrapping Calendar.getInstance()) and then mocking this in my test. Then my mock could return whatever time I wanted.

The problem was that the mock was called more than once and always returned the *same* calendar instance. The code would then manipulate this calendar to do time calculations but because each call returned the same instance this had undesirable effects.

The solution was to use the Mockito stubbing API with the mock. You can create a callback that is called each time the mock interface is called and you can have it do whatever you want. I simple set it up to return a new instance each time

    @Mock CalendarFacade        mockCalendarFacade;

    private void setupCalendarWithTimeInPastMock(final int minutesAgo)
    {
        stub(mockCalendarFacade.getCalendar()).toAnswer(new Answer()
        {
            public Calendar answer(InvocationOnMock invocation)
            {
                return calendarMinutesAgo(minutesAgo);
            }
        });
    }

    private Calendar calendarMinutesAgo(Integer minutes)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,-minutes);
        return calendar;
    }

No comments:

Post a Comment