【问题标题】:How to mock a protected computed read-only property using Rhino Mocks?如何使用 Rhino Mocks 模拟受保护的计算只读属性?
【发布时间】:2013-08-30 19:00:12
【问题描述】:

我有这样的事情:

public class SomeClass
{
    protected ISomeInterface SomeProperty
    {
        get { return SomeStaticClass.GetSomeInterfaceImpl(); }
    }

    public void SomeMethod()
    {
        // uses SomeProperty in calculations
    }
}

如何测试 SomeMethod,使用 Rhino Mocks 模拟 SomeProperty?我正在考虑获取访问器,使用 IL 重写访问器,只是为了返回模拟代理。听起来有多疯狂?

【问题讨论】:

  • 我建议重构您的代码,以便将ISomeInterface 注入SomeClass。现在,你有一个 SomeStaticClass 形式的硬依赖,这很难有效地模拟。
  • 为什么首先要保护财产?
  • 不幸的是,这是无法更改的 DLL 的一部分(商业原因)。

标签: c# reflection rhino-mocks


【解决方案1】:

您不能模拟被测类,只能模拟依赖项。因此,如果您使用某种工厂而不是 SomeStaticClas 并使用 SomeClass 的构造函数参数注入它,您就可以模拟工厂类。

public class SomeClass
{
    public SomeClass(ISomeInterfaceFactory factory)
    {
        this.factory = factory;
    }

    protected ISomeInterface SomeProperty
    {
        get { return factory.GetSomeInterface(); }
    }

    public void SomeMethod()
    {
        // uses SomeProperty in calculations
    }
}

public interface ISomeInterfaceFactory
{
    ISomeInterface GetSomeInterface();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多