gpt4 book ai didi

C# 模拟具体类。如何?

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:58 25 4
gpt4 key购买 nike

我想模拟一个具体的类,具体来说是 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 中以这种方式编写单元测试?或者您不为已知的限制走这条路?

非常感谢您的帮助。

最佳答案

另一种方法是使用允许您模拟具体类的单元测试工具,例如我正在使用 Typemock Isolator 并且能够创建您想要进行的测试:

[TestMethod]
public void TestMethod1()
{
var fakeLocationMap = Isolate.Fake.Instance<SortedDictionary<string, Location>>();

Isolate.WhenCalled(() => fakeLocationMap.ContainsKey(string.Empty)).WillReturn(true);

var instance = new LocationMapper(fakeLocationMap);
var res = instance.AddLocation(new Location("a"));

Isolate.Verify.WasNotCalled(() => fakeLocationMap.Add(string.Empty, null));
}

关于C# 模拟具体类。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42681474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com