我想嘲笑一个具体的类,具体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