如何使对象与非虚拟函数的单元测试模拟 [英] How to make a unit test mock of an object with non-virtual functions

查看:120
本文介绍了如何使对象与非虚拟函数的单元测试模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有被使用Wsdl.exe工具,看起来像这样生成的C#类:

I have a C# class that gets generated using the wsdl.exe tool that looks something like this:

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



我身边有一些这方面的瘦包装代码,跟踪结果等的是否有可能使用任何嘲笑框架对象,以使假SoapApi类,并返回针对每个呼叫的预测的结果,以薄包装函数

I have some thin wrapper code around this that keeps track of the result, etc. Is it possible to use any of the object mocking frameworks to make a fake SoapApi class and return predictable results for each of the calls to the thin wrapper functions?

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

I can't make the AskServerQuestion() function virtual because it's auto-generated by the wsdl.exe tool.

推荐答案

我已经完成了这个问题的方法是不是一个注入ISoapApi,其中ISoapApi界面模仿自动生成的SOAP API

The way I've accomplished this was to inject an ISoapApi instead, where the ISoapApi interface mimics the automatically generated SOAP API.

有关你的情况:

public interface ISoapApi
{
    SOAPTypeEnum AskServerQuestion ();
}



然后,利用这样的事实所生成的SoapApi类是局部的优势,并且在另一个文件补充一点:

Then, take advantage of the fact that the generated SoapApi class is partial, and add this in another file:

public partial class SoapApi : ISoapApi
{
}

那么,消费者应该只取可以被任何嘲讽的框架被嘲笑的ISoapApi依赖。

Then, consumers should just take an ISoapApi dependency that can be mocked by any of the mocking frameworks.

一个缺点是当然,当SOAP API的变化,你需要更新你的接口定义为好。

One downside is, of course, when the SOAP api changes, you need to update your interface definition as well.

这篇关于如何使对象与非虚拟函数的单元测试模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆