The Effective Java has the following statement on unit testing singletons
Making a class a singleton can make it difficult to test its clients, as it’s im
Singleton objects are created without any control from the outside. In one of the other chapters of the same book Bloch suggests using enum
s as default Singleton implementation. Let's see an example
public enum Day {
MON(2), TUE(3), WED(4), THU(5), FRI(6), SAT(7), SUN(1);
private final int index;
private Day(int index) {
this.index = index;
}
public boolean isToday() {
return index == new GregorianCalendar().get(Calendar.DAY_OF_WEEK);
}
}
Let's say we have a code that should be executed only on weekends:
public void leisure() {
if (Day.SAT.isToday() || Day.SUN.isToday()) {
haveSomeFun();
return;
}
doSomeWork();
}
Testing leisure method is going to be pretty hard. Its execution is going to be dependent on the day when it is executed. If it executes on a weekday doSomeWork()
will be invoked and on weekends haveSomeFun()
.
For this case we would need to use some heavy tools like PowerMock to intercept the GregorianCalendar
constructor, return a mock which will return an index corresponding to a weekday or weekend in two test cases testing both execution paths of the leisure
method.