我有一个单例,可以通过如下静态属性在我的类中访问:OtherClassNotBeingTested.Instance.SomeInstanceMethod()
我想在不制作这些对象之一的情况下测试我的课程。当调用静态属性的 getter 时,RhinoMocks 有没有办法返回存根Instance
?
为了更清楚,这里是 Instance 属性的代码:
/// <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;
}
}
更新:这就是我最终修复它的方式:
class ClassBeingTested
{
public ClassBeingTested(IGuiInterface iGui):this(iGui, Control.Instance)
{
}
public ClassBeingTested(IGuiInterface iGui, IControl control)
{
mControl = control;
//Real Constructor here
}
}
我的单元测试调用第二个构造函数。实际代码调用第一个构造函数。类中的代码使用本地字段mControl而不是单例。(我认为这称为依赖注入。)
我还按照Tony the Pony的建议重构了 Singleton。