[英]Stub a readonly property in a baseclass
我有這樣的課:
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");
}
}
}
所以我的問題是,如何對只讀屬性進行存根/填充,以便可以測試此功能?
將此吸氣劑包裝到可以被模擬覆蓋的臨時虛擬方法中怎么辦?
例如:
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");
看起來有點像有效使用遺留代碼中 Introduce Instance Delegator
模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.