Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何对具有非虚拟函数的对象进行单元测试模拟_C#_Unit Testing_Mocking - Fatal编程技术网

C# 如何对具有非虚拟函数的对象进行单元测试模拟

C# 如何对具有非虚拟函数的对象进行单元测试模拟,c#,unit-testing,mocking,C#,Unit Testing,Mocking,我有一个C#类,它是使用wsdl.exe工具生成的,看起来像这样: public partial class SoapApi : System.Web.Services.Protocols.SoapHttpClientProtocol { public SOAPTypeEnum AskServerQuestion() { object[] results = return this.Invoke("AskServerQuestion"); retu

我有一个C#类,它是使用wsdl.exe工具生成的,看起来像这样:

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();
}
现在创建一个新类,该类继承上述两个类:

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

现在,您可以在程序中使用
SomeClass2
。它的行为与
SomeClass
相同。你也可以模仿我的课

非常感谢,工作得很有魅力。我不得不添加一些东西,因为生成的类实现了另一个接口,但这绝对是正确的路径。我希望用于C#的wsdl工具在使用web服务时自动生成服务接口,以避免我们的麻烦,但遗憾的是,我一直找不到任何方法使其能够做到这一点。