2011-01-12 44 views
0

嘲讽私有字段我有以下的类定义,由此attribute字段经由反射由NHibernate的水合。现场没有公开为对象,而是我想隐藏它的实现,只是提供参考attribute领域的性能特性。与RhinoMocks

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(); 

    } 

回答

0

如果CustomerAttribute正在测试(SUT)和IAttribute你的主题是需要进行模拟来测试的依赖,IAttribute更可能需要将注入到CustomerAttribute中。这应该通过构造函数(通常是首选)或属性注入完成。如果您不熟悉它,请查看“控制反转”。

此外,ICustomerAttribute不应该被创建为一个模拟 - 具体类型应该被显式地创建(即,“新CustomerAttribute”)。毕竟,CustomerAttribute(实现!)是你试图测试的东西。

0

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

为了设置你的CustomerAttribute属性,你既可以

  • 使用dependency injection注入正确的属性和测试
  • 真正CustomerAttribute实例的使用反射过程中使用它,你测试
  • 创建