我有一个在我的类中通过静态属性访问的单例,如下所示:OtherClassNotBeingTested.Instance.SomeInstanceMethod()
我想在不制作这些对象之一的情况下测试我的类(class)。当调用静态属性 Instance
的 getter 时,RhinoMocks 是否有办法返回 stub ?
为了更清楚,这是实例属性的代码:
/// <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 而不是单例。 (我认为这叫做依赖注入(inject)。)
我还按照小马托尼的建议重构了单例。
最佳答案
我希望您的mInstance
变量被声明为volatile,否则您的DCL 实现将被破坏。说真的,你真的需要那种程度的懒惰吗?我个人会推荐一些 simpler patterns available .
但是,当谈到模拟时 - 不,您不能使用 RhinoMocks 模拟静态调用。有一些可用的工具可以做到这一点,例如 Typemock ,但我个人首先会重构该应用,使其更易于测试。
另一种选择是拥有一个“作弊”单例,您可以在其中设置测试用例中单例属性的值。如果让属性返回一个接口(interface)而不是单例类本身,则可以用模拟替换真正的单例。
关于c# - Rhino Mocks - stub 一个单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1664413/