Tue
1
Feb '05
Mock objects
by Frank Spychalski filed under articles, Java, Work

If you find this useful, you might like my other articles, too.

In Mock Objects in Unit Tests Lu Jian writes about two tools (EasyMock and Mocquer) which generate mock objects. Here’s my most frequently used mock object.

Disclaimer: I know one could argue whether this is a ‘real’ mock object or more of a mock object facade bastard thingy.

I use Clock everywhere I would call System.currentTimeMillis() or call Calendar.get(...). This gives me an easy way to fast-forward in time without sleeps during unit tests.

public class Clock {

// some methods left out for clarity
private static boolean debugMode = false;
/** * dummy time, default value of 0 produced some strange errors in some tests */ private static long lMillis = 12341234; private static int hour;
private Clock() { // no instances needed } /** * facade for System.currentTimeMillis() */ public static long currentTimeMillis() { if (debugMode) { return lMillis; } return System.currentTimeMillis(); }
/** * facade for Calendar.get(Calendar.HOUR_OF_DAY) */ public static int getHour() { if (debugMode) { return hour; } final Calendar c = Calendar.getInstance(); return c.get(Calendar.HOUR_OF_DAY); }
public static void setDebugMode(boolean b) { debugMode = b; }
private static void checkDebug() { if (!debugMode) { throw new IllegalStateException("You cannot set or change time now. Turn on debug mode first"); } }
public static void setCurrentTimeMillis(final long l) { checkDebug(); lMillis = l; }
public static void addCurrentTimeMillis(final long l) { checkDebug(); lMillis += l; }
public static void setHour(final int i) { checkDebug(); if (i < 0 || i > 23) { throw new IllegalArgumentException("hour '" + i + "'"); } hour = i; } }

Any comments? Or questions? Just leave a Reply: