The Singleton Pattern and How to Fake It
The singleton pattern is well known and used in many software projects. Faking Singleton can be done by replacing the singleton class on creation or by faking the property (or method) that returns the singleton.
1. Fake the next instance of the class – by using Swap.NextInstance to replace the next object instantiation with our fake class:
1 2 3 4 5 6 7 8 9 |
var fake = Isolate.Fake.Instance<SingletonClass>(); <span class="rem">// Set additional behavior on singleton class</span> Isolate.WhenCalled(() => fake.SomeFunction()).WillReturn(10); Isolate.Swap.NextInstance<SingletonClass>().With(fake); <span class="rem">// This is where the class constructor is being called</span> var result = SingletonClass.GetInstace().SomeFunction(); |
1 |
Assert.AreEqual(10, result ); |
2. Fake the Current/Instance property – If the singleton object created before the test starts we can fake the property/method that returns the singleton instead:
1 2 3 4 5 6 7 8 9 |
var fake = Isolate.Fake.Instance<SingletonClass>(); Isolate.WhenCalled(() => fake.SomeFunction()).WillReturn(10); Isolate.WhenCalled(() => SingletonClass.GetInstace()).WillReturn(fake); <span class="rem">// Test the result</span> var result = SingletonClass.GetInstace().SomeFunction(); Assert.AreEqual(10, result ); |
It’s that simple…