我想模拟一个具体的类,具体来说就是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中以这种风格编写单元测试?还是您不采用已知约束的方法?非常感谢您的帮助。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 另一种方法是使用一个单元测试工具,该工具允许您模拟具体的类,例如,我正在使用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));} (adsbygoogle = window.adsbygoogle || []).push({});
08-19 09:54