Rhino Mocks - Piece a Singleton

I have a Singleton that is available in my class through a static property similar to this: OtherClassNotBeingTested.Instance.SomeInstanceMethod()

I would like to test my class without creating one of these objects. Is there a way for RhinoMocks to return a stub when getter is called for a static property Instance?

To be more clear, here is the code for the instance property:

    /// <summary>
    /// Make a property to allow the OtherClassNotBeingTested class 
    ///   to be a singleton 
    /// </summary>
    public static OtherClassNotBeingTested Instance
    {
        get
        {
            // Check that the instance is null
            //  NOTE: COMMENTS BELOW HAVE SHOWN THIS TO BE BAD CODE.  DO NOT COPY
            if (mInstance == null)
            {
                // Lock the object
                lock (mSyncRoot)
                {
                    // Check to make sure its null
                    if (mInstance == null)
                    {
                        mInstance = new OtherClassNotBeingTested();
                    }
                }
            }

            // Return the non-null instance of Singleton
            return mInstance;
        }
    }

Update: Here is how I fixed it:

class ClassBeingTested
{
    public ClassBeingTested(IGuiInterface iGui):this(iGui, Control.Instance)
    {

    }

    public ClassBeingTested(IGuiInterface iGui, IControl control)
    {
        mControl = control;

        //Real Constructor here
    }
}

My unit tests call the second constructor. The actual code calls the first constructor. The code in the class uses the local mControl field instead of singleton. (I think this is called dependency injection.)

I also reorganized Singleton as suggested by Tony Pony.

+3
2

, mInstance ​​, DCL . , ? , .

, - , RhinoMocks. , , Typemock, , .

"" , singleton . singleton, .

+4

, , . :

?

, . , .

+4

Source: https://habr.com/ru/post/1721745/


All Articles