我想嘲笑一個具體的類,具體SortedDictionary。C#模擬具體類。怎麼樣?
上下文:
我有定義爲低於LocationMapper類:
public class LocationMapper
{
private SortedDictionary<string, Location>() locationMap;
public LocationMapper()
{
this.locationMap = new SortedDictionary<string, Location>();
}
public LocationMapper(SortedDictionary<string, Location> locations)
{
this.locationMap = locations;
}
public Location AddLocation(Location location)
{
if(! locationMap.ContainsKey(location.Name))
{
locationMap.Add(location.Name, location)
}
return locationMap[location.Name];
}
}
單元測試AddLocation(),我需要模擬具體類SortedDictionary <>。不幸的是,NSubstitute不允許它。
The unit test that I had envisioned to write is below
[Test]
public void AddLocation_ShouldNotAddLocationAgainWhenAlreadyPresent()
{
var mockLocationMap = ;//TODO
//Stub mockLocationMap.ContainsKey(Any<String>) to return "true"
locationMapper = new LocationMapper(mockLocationMap);
locationMapper.AddLocation(new Location("a"));
//Verify that mockLocationMap.Add(..) is not called
}
你怎麼會去用這種方式在DOTNET的編寫單元測試?或者你不採取這種已知約束的路徑?
您的幫助是非常感謝。
爲什麼嘲笑呢?爲什麼不創建一個實例並將其傳入?你有完全的控制來填補它,但是你想,所以我認爲你可以斷言結果。如果它是一個接口,那麼肯定是模擬的,但用一個具體的字典,我不認爲它是需要的。 – TyCobb
你究竟在測試什麼?在我看來,你實際上正在測試SortedDictionary做它保證做的事情。你希望達到什麼價值? –
@TyCobb,我已經用我的單元測試偏好/偏好作爲模板單元測試用例更新了這個問題,供您細讀。 – karthiks