![](/img/trans.png)
[英]How to Mock a readonly property whose value depends on another property of the Mock
[英]How do I mock or stub a method from a readonly property whose datatype is dictionary?
我開始使用犀牛模型,遇到了一個復雜的問題。
我對類AppDefaults有依賴關系,該類具有只讀屬性“ Properties”,其數據類型為Dictionary。
我的被測類使用Dictionary函數.ContainsKey()的結果,該函數返回一個布爾值。
MyAppDefaultsInstance.Properties.ContainsKey(“ DefaultKey”)
我只是通過在要測試的類上創建一個公共虛擬函數來包裝.Contains函數來解決此問題。 但是有沒有一種方法可以模擬或存根.ContainsKey結果而無需包裝器來模擬它?
示例代碼:
public class AppDefaults
{
public readonly IDictionary<String, String> Properties = new Dictionary<string, string>();
public AppDefaults()
{
LoadProperties();
}
private void LoadProperties()
{
//load the properties;
}
public virtual int GetPropertyAsInt(string propertyKey)
{
return XmlConvert.ToInt32(Properties[propertyKey]);
}
}
public class DefaultManager
{
AppDefaults _appsDefault;
public int TheDefaultSize
{
get
{
int systemMax;
int currentDefault = 10;
if (_appsDefault.Properties.ContainsKey("DefaultKey"))
{
systemMax = _appsDefault.GetPropertyAsInt("DefaultKey");
}
else
{
systemMax = currentDefault;
}
return systemMax;
}
}
public DefaultManager(AppDefaults appDef) {
_appsDefault = appDef;
}
}
[TestClass()]
public class DefaultManagerTest
{
[TestMethod()]
public void TheDefaultSizeTest()
{
var appdef = MockRepository.GenerateStub<AppDefaults>();
appdef.Expect(m => m.Properties.ContainsKey("DefaultKey")).Return(true);
appdef.Stub(app_def => app_def.GetPropertyAsInt("DefaultKey")).Return(2);
DefaultManager target = new DefaultManager(appdef);
int actual;
actual = target.TheDefaultSize;
Assert.AreEqual(actual, 2);
}
}
為什么不嘲笑.ContainsKey
方法,而不是只用一些預定義的測試值填充字典:
// arrange
var appDef = new AppDefaults();
appDef.Properties["DefaultKey"] = "2";
// act
var target = new DefaultManager(appDef);
// assert
Assert.AreEqual(target.TheDefaultSize, 2);
我不會暴露
AppDefaults.Properties
領域。 除此之外,您可以添加類似
GetProperty(string key)
到AppDefaults(如果存在則返回鍵),然后在單元測試中模擬結果。 模擬的方法都將返回將檢查target.TheDefaultSize對值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.