Quick tip – How to fake a singleton

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.

image

  1. Fake the next instance of the class – by using Swap.NextInstance to replace the next object instantiation with our fake class:
    var fake = Isolate.Fake.Instance<SingletonClass>();

    // Set additional behavior on singleton class
    Isolate.WhenCalled(() => fake.SomeFunction()).WillReturn(10);

    Isolate.Swap.NextInstance<SingletonClass>().With(fake);

    // This is where the class constructor is being called
    var result = SingletonClass.GetInstace().SomeFunction();

    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:
    var fake = Isolate.Fake.Instance<SingletonClass>();

    Isolate.WhenCalled(() => fake.SomeFunction()).WillReturn(10);
    Isolate.WhenCalled(() => SingletonClass.GetInstace()).WillReturn(fake);

    // Test the result
    var result = SingletonClass.GetInstace().SomeFunction();

    Assert.AreEqual(10, result );

It’s that simple…

  • Eli Lopian

    Probably the best way would be to use Swap.AllInstances when it is released.

    Isolate.Swap.AllInstances[SingletonClass]().With(fake);

    This will handle both the case where the singleton is created and the case where the singleton is already in memory.

TOP