【发布时间】:2017-03-08 20:38:20
【问题描述】:
我想模拟一个具体的类,具体来说是 SortedDictionary。
上下文:
我有一个 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 中以这种风格编写单元测试?或者你不为已知的约束选择这条路?
非常感谢您的帮助。
【问题讨论】:
-
为什么要嘲笑它?为什么不直接创建一个实例并传入呢?您可以根据需要完全控制填充它,所以我认为您可以断言结果。如果它是一个接口,那么肯定是模拟的,但是使用具体的字典,我认为不需要它。
-
您实际测试的是什么?在我看来,您实际上是在测试 SortedDictionary 是否做了它保证做的事情。您希望实现什么价值?
-
@TyCobb,我已经用我的单元测试偏见/偏好作为模板单元测试用例更新了这个问题,供您阅读。
-
验证 mockLocationMap.Add(..) 未被调用 -- 使用具体实例,添加“a”并断言有 1 个项目。再次添加“a”并断言仍然只有 1 并且尝试添加重复键并没有爆炸
标签: c# unit-testing mocking tdd