使用 NSubstitute 模拟 Web 服务时出错
Error Mocking a webservice with NSubstitute
我正在尝试模拟一个继承自 SoapHttpClientProtocol
且我无法在单元测试中修改的 Web 服务对象。不幸的是,当我尝试时:
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 方代码)。抽象所需的行为并将第 3 方代码封装在您的抽象实现中。
public interface IMyApiInterface {
//...code removed for brevity
}
将抽象注入它们的依赖项类。这将允许更好地模拟您的单元测试和整体更多 flexible/maintainable 架构。
var myApi = Substitute.For<IMyApiInterface>();
接口的实际实现将封装或组合实际的 Web 服务。
public class MyProductionAPIClass : MyAPIClass, IMyApiInterface {
//...code removed for brevity
}
不要将您的代码与不允许灵活和可维护代码的实现问题紧密耦合。取而代之的是抽象。
我正在尝试模拟一个继承自 SoapHttpClientProtocol
且我无法在单元测试中修改的 Web 服务对象。不幸的是,当我尝试时:
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 方代码)。抽象所需的行为并将第 3 方代码封装在您的抽象实现中。
public interface IMyApiInterface {
//...code removed for brevity
}
将抽象注入它们的依赖项类。这将允许更好地模拟您的单元测试和整体更多 flexible/maintainable 架构。
var myApi = Substitute.For<IMyApiInterface>();
接口的实际实现将封装或组合实际的 Web 服务。
public class MyProductionAPIClass : MyAPIClass, IMyApiInterface {
//...code removed for brevity
}
不要将您的代码与不允许灵活和可维护代码的实现问题紧密耦合。取而代之的是抽象。