[英]Rhino Mocks - Stub a Singleton
我有一个Singleton,该类可以通过这样的静态属性在我的班级中访问: OtherClassNotBeingTested.Instance.SomeInstanceMethod()
我想测试我的班级而无需制造这些对象之一。 调用静态属性Instance
的getter时,RhinoMocks是否可以返回存根?
为了更清楚,这是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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.