我有一个这样的课程:
public class Customer : CustomerBase
{
// internals are visible to test
internal string GenString()
{
// this actually composes a number of different properties
// from the parent, child and system properties
return this.InfoProperty.Name + DateTime.Now.ToString() + "something else";
}
}
// this class is in a 3rd party library, but from metadata it looks like this
public class CustomerBase
{
public Info InfoProperty { get; }
}
我的测试看起来像这样:
public class Tests
{
public void MyTest()
{
using (ShimsContext.Create())
{
// Arrange
/* I shim datetime etc. static calls */
Fakes.StubCustomer c = new Fakes.StubCustomer()
{
InfoProperty = new Info("Name") // <- Error here because it's readonly
};
// Act
string result = c.GenString();
// Assert
Assert.AreEqual(result, "whatnot");
}
}
}
所以我的问题是,我如何存根/ shim readonly属性,以便我可以测试这个函数?
答案 0 :(得分:0)
如果将这个getter包装在一个可被模拟覆盖的临时虚拟方法中呢?
例如:
public class Customer : CustomerBase
{
// internals are visible to test
internal string GenString()
{
// this actually composes a number of different properties
// from the parent, child and system properties
return InfoPropertyNameGetter() + DateTime.Now.ToString() + "something else";
}
public virtual string InfoPropertyNameGetter(){
retrn this.InfoProperty.Name;
}
}
Mock<Customer> mock = new Mock<Customer>();
mock.Setup(m => m.InfoPropertyNameGetter()).Returns("My custom value");
它看起来有点像Working effectively with legacy code
中描述的Introduce Instance Delegator
模式