c# - 使用 NSubstitute 模拟 Web 服务时出错

标签 c# .net unit-testing nsubstitute

我正在尝试模拟一个继承自 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/

相关文章:

c# - 后面的代码如何从另一个类访问HTTP请求信息

c# - UTF8Encoding string to byte[] 转换意外行为

.net - 使用Orleans,如何实现分布式计算和分布式数据存储?

c# - 在 .net Windows 窗体中保留字符串值

c# - 需要使用 NUnit 测试 Controller HTTP 方法

java - 如何在 Mockito 和 JUnit 中模拟具有复杂请求的服务?

c# - ASPxPageControl 从 javascript 切换选项卡

c# - 将 NetTCPBinding 与 TcpClientCredentialType.Windows 结合使用的 WCF 安全性

javascript - Jest- JSDOM 在实例化 JSDOM 时将 HTML 传递给 Jest 中的 JSDOM 构造函数

c# - Linq 过滤历史记录中的行差异