【问题标题】:Mocking private fields with RhinoMocks使用 RhinoMocks 模拟私有字段
【发布时间】:2011-01-12 18:46:39
【问题描述】:

我有以下类定义,其中 attribute 字段通过 NHibernate 的反射进行水合。该字段没有作为对象公开,而是我想隐藏它的实现,只提供引用 attribute 字段属性的属性。

    public class CustomerAttribute : ICustomerAttribute
{
    private IAttribute attribute;

    public string DisplayName 
    {
      get { return attribute.DisplayName;}

    }

}

我正在尝试使用 RhinoMocks 模拟此对象,但我不确定如何为 attribute 字段添加水分以进行测试。我尝试通过反射手动设置attribute 字段,但我从RhinoMocks 收到代理错误(这是有道理的)。

那么我如何为attribute 字段添加水分以测试 CustomerAttribute 对象的属性?

这是我现在的测试...

        [Test]
    public void PropertiesTest()
    {
        MockRepository mock = new MockRepository();
        ICustomerAttribute attribute = mock.StrictMock<ICustomerAttribute>();

        //Set the attribute field
        FieldInfo fieldInfo = typeof(CustomerAttribute).GetField("attribute",
                                                      BindingFlags.Instance | BindingFlags.SetField |
                                                      BindingFlags.NonPublic);

        fieldInfo.SetValue(attribute, new Domain.Attribute()); //This does not work

        Expect.Call(attribute.DisplayName).Return("Postal Code");
        mock.ReplayAll();

        Assert.AreEqual(true, attribute.DisplayName);
        mock.VerifyAll();

    }

【问题讨论】:

    标签: rhino-mocks field private


    【解决方案1】:

    如果 CustomerAttribute 是您的测试对象 (SUT),而 IAttribute 是需要模拟以进行测试的依赖项,则 IAttribute 很可能需要注入到 CustomerAttribute 中。这应该通过构造函数(通常是首选)或属性注入来完成。如果您还不熟悉“控制反转”,请查看它。

    此外,不应将 ICustomerAttribute 创建为模拟 - 应显式创建具体类型(即“新 CustomerAttribute”)。毕竟,CustomerAttribute(实现!)是您要测试的内容。

    【讨论】:

      【解决方案2】:

      我不确定您要在这里测试什么。如果您想测试您的 CustomerAttribute 类,则需要创建它的实例(而不是模拟 ICustomerAttribute)。

      为了在您的 CustomerAttribute 上设置属性,您可以

      • 使用dependency injection 注入正确的属性并在测试期间使用它
      • 使用您为测试创建的真实 CustomerAttribute 实例的反射

      【讨论】:

        猜你喜欢
        • 2012-06-28
        • 1970-01-01
        • 2010-10-09
        • 2013-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        • 1970-01-01
        相关资源
        最近更新 更多