犀牛模拟 - 单根单人
-
12-09-2019 - |
题
我有一个单身人士,可以通过这样的静态属性在我的班级中访问:OtherClassNotBeingTested.Instance.SomeInstanceMethod()
我想通过制作这些对象之一来测试我的班级。有没有办法让犀牛在静态属性的GETTER时返回存根 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 而不是单身人士。 (我认为这称为依赖注入。)
我还根据 小马托尼的建议。
其他提示
不隶属于 StackOverflow