Kasper Munck

Unit Testing Singletons

Whether to use singletons or not is a matter of religion and I won't be judging anyone. In my opinion there are certain situations where singletons just make our lives easier, hence I introduce a singleton every now and then, when appropriate. However, testing singletons is no easy task, which is why I tend to avoid it.

In an attempt to make things easier, I created KMSwizzleton, a helper class that aims to inject mock instances into a singleton object (assuming that you follow the sharedInstance).

id fakeSingleton = [OCMockObject mockForClass:[MySingleton class]]; // or any other mock library
[KMSwizzleton stubSingleton:[MySingleton class] andReturnFakeInstance:fakeSingleton];
id instance = [MySingleton sharedInstance]; // returns fakeSingleton

This makes it possible to inject a stub or mock singleton into a closed method, which otherwise would be quite a hassle. It also gets rid of the need to expose a property injection method, dealing with a private class extension or to override +sharedInstance in a testable subclass of MySingleton. After +sharedInstance is called once, MySingleton is reverted to its original state.

[ unit testing singleton sharedInstance KMSwizzleton ]