How to Mock a Static Singleton?

JamesEggers picture JamesEggers · Jan 12, 2010 · Viewed 20.5k times · Source

I have number of classes I've been asked to add some unit tests to with Rhino Mocks and having some issues.

First off, I know RhinoMocks doesn't allow for the mocking of Static members. I'm looking for what options I have (besides using TypeMock).

An example of the class I have is similar to the below:

class Example1 : ISomeInterface
{
    private static ISomeInterface _instance;

    private Example1()
    {
        // set properties via private static methods
    }

    static Example1()
    {
        _instance = new Example1();
    }

    public static ISomeInterface Instance() 
    {
        get { return _instance; }
    }

    // Instance properties 

    // Other Instance Properties that represent objects that follow a similar pattern.
}

So when I call the above class, it looks something like this...

Example1.Instance.SomeObject.GoDownARabbitHole();

Is there a way for me to mock out the SomeObject.GoDownARabbitHole() in this situation or mock out the Instance?

Answer

No answer picture No answer · Aug 19, 2013

Discouraged by threads like this, it took me quite some time to notice, that singletons are not that hard to mock. After all why are we using c#?

Just use Reflection.

With provided sample code you need to make sure the static constructor is called before setting the static field to the mocked object. Otherwise it might overwrite your mocked object. Just call anything on the singleton that has no effect before setting up the test.

ISomeInterface unused = Singleton.Instance();

System.Reflection.FieldInfo instance = typeof(Example1).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

Mock<ISomeInterface> mockSingleton = new Mock<ISomeInterface>();
instance.SetValue(null, mockSingleton.Object);

I provided code for mocking with Moq, but I guess Rhino Mocks is quite similar.