At first sight it may seem that Singleton and Unit Testing are not compatible since you cannot ensure the separation between the tests. We could solve the problem by instanciating a new "Singleton" instance for each test and apply test on this "local" instance. The problem is that a well implemented Singleton is sealed and it's constructor are private (see Singleton Pattern here) and thus you cannot create this instance.
using System; public sealed class Singleton { ... private Singleton() {} public static Singleton Instance { get { ...} } }
Reflection to the rescue
An elegant way for bypassing the "creation problem" is to use Reflection to get the private constructor (ConstructorInfo) and then use this constructor info to create a new "Singleton" instance.
using System.Reflection; [TestFixture] public class SingletonTest { private Singleton target = null; [SetUp] public void SetUp() { ConstructorInfo ci = typeof(Singleton).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null ); Assert.IsNotNull(ci); this.target = (Singleton)ci.Invoke(null); } }
Now we have a new instance of the Singleton for each test and we are happy.
Page rendered at Monday, October 13, 2008 11:46:04 AM UTC
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.