mardi 1 mars 2016

Create Dummy-instance for singleton

I have a singleton-class that I want to mock for testing as follows:

public class MyClass {
    private readonly static MyClass _instance = new MyClass();
    public MyClass Instance { get { return this._instance; }}

    private MyClass() 
    {
        DoSomething();
    }
}

As the private constructor of MyClass has some havy logic including reading some config-file I want to mock the single-ton-instance for testing-purposes. However I can´t see any way on doing this as I can´t mark the property Instance virtual.

I think I have to oppourtunities, but I don´t know which fits better. The first one is making the (private) DomeSomething-method overridable (meaning protected and virtual) and create some dummy-implementation for it in a derived class (the mock). However modifying my class-structure for the sake of testing does not seem right to me.

The other way could be by using FormatterServices.GetUninitializedObject() as suggested in this approach. I´d simply create an instance without setting any of its members. Afterwards I could intialize the members I need by reflection using some simpler logic. Anyway this also seems quite crude to me.

Are there any other opportunities I have? Or do I have to chose between those two annoying ones?





Aucun commentaire:

Enregistrer un commentaire