如何使用非虚函数对单元进行unit testing模拟

我有一个使用wsdl.exe工具生成的C#类,如下所示:

public partial class SoapApi : System.Web.Services.Protocols.SoapHttpClientProtocol { public SOAPTypeEnum AskServerQuestion() { object[] results = return this.Invoke("AskServerQuestion"); return (SOAPTypeEnum) results[0]; } } 

我有一些瘦的包装代码来跟踪结果,等等。是否可以使用任何对象模拟框架来制作一个假的SoapApi类,并为每个对瘦包装函数的调用返回可预测的结果?

我不能将AskServerQuestion()函数设置为虚拟,因为它是由wsdl.exe工具自动生成的。

我完成这个的方法是注入一个ISoapApi,其中ISoapApi接口模仿自动生成的SOAP API。

对于你的情况:

 public interface ISoapApi { SOAPTypeEnum AskServerQuestion (); } 

然后,利用生成的SoapApi类是部分的这一事实,并将其添加到另一个文件中:

 public partial class SoapApi : ISoapApi { } 

然后,消费者应该采用可由任何模拟框架模拟的ISoapApi依赖项。

当然,一个缺点是当SOAP api发生变化时,您还需要更新接口定义。

该类是部分的,因此您可以使类在您编写的部分类部分中实现接口。 然后,您可以模拟界面。

我找到了一种技术,适用于类非局部的情况 。 假设这是原始类:

 // Generated class, can't modify. public class SomeClass { // Non-virtual function, can't mock. public void SomeFunc() { //... } } 

首先,从该类中提取接口:

 public interface ISomeClass { void SomeFunc(); } 

现在创建一个inheritance上述两个类的新类:

 public SomeClass2 : SomeClass, ISomeClass { // The body of this class is empty. } 

现在,您可以在程序中使用SomeClass2 。 它的行为与SomeClass相同。 你可以模拟ISomeClass