我正在尝试模拟一个继承自 SoapHttpClientProtocol
的 Webservice 对象,并且我无法在单元测试中对其进行修改。不幸的是,当我尝试时:
var myApi = Substitute.ForPartsOf<MyAPIClass>();
我收到以下错误:
Message: Test method MyProj.Test.Business.Folder.CalendarEventServiceUnitTest.GetPerformances_WithEventsAndPerformances_CorrectlyDistinguishesThem threw exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: There was an error reflecting type 'MyNamespace.MyAPIClass'. ---> System.InvalidOperationException: Cannot serialize member 'System.ComponentModel.Component.Site' of type 'System.ComponentModel.ISite', see inner exception for more details. ---> System.NotSupportedException: Cannot serialize member System.ComponentModel.Component.Site of type System.ComponentModel.ISite because it is an interface.
最佳答案
不要尝试模拟您无法控制的代码(即第 3 方代码)。抽象所需的行为并将第三方代码封装在抽象的实现中。
public interface IMyApiInterface {
//...code removed for brevity
}
将抽象注入(inject)到它们的依赖类中。这将允许更好地模拟单元测试,并总体上提供更灵活/可维护的架构。
var myApi = Substitute.For<IMyApiInterface>();
接口(interface)的实际实现将封装或组合实际的 Web 服务。
public class MyProductionAPIClass : MyAPIClass, IMyApiInterface {
//...code removed for brevity
}
不要将您的代码与不允许灵活且可维护的代码的实现问题紧密耦合。相反,依赖于抽象。
关于c# - 使用 NSubstitute 模拟 Web 服务时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44311832/