Singleton and unit testing

user2434 picture user2434 · Nov 24, 2011 · Viewed 38.7k times · Source

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 impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.

Can anyone explain the why this is so ?

Answer

TedEd picture TedEd · Jan 19, 2015

You could use reflection to reset your singleton object to prevent tests from affecting each other.

@Before
public void resetSingleton() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
   Field instance = MySingleton.class.getDeclaredField("instance");
   instance.setAccessible(true);
   instance.set(null, null);
}

Ref: unit-testing-singletons