I have a Singleton that is accessed in my class via a static property like this:OtherClassNotBeingTested.Instance.SomeInstanceMethod()
I would like to test my class with out making one of these objects. Is there a way for RhinoMocks to return a stub when the getter for the static property Instance
is called?
To be clearer, 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: This is how I ended up fixing 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 field mControl instead of the singleton. (I think this is called dependency injection.)
I also refactored the Singleton as per Tony the Pony's suggestion.