【问题标题】:Add unit test case to test external webservice (.asmx) .NET添加单元测试用例以测试外部 Web 服务 (.asmx) .NET
【发布时间】:2013-09-06 06:12:29
【问题描述】:

我编写了一个代码来读取外部 Web 服务并使用 System.Web.Services.ServiceDescription 查找公开方法及其参数。 我还可以调用该方法并通过 web 服务获取输出。 这仅在外部 Web 服务 Url 的基础上完成。

一切都通过 CodeBehind (C#) 完成。

我需要添加单元测试用例来测试功能,方法是添加将由单元测试访问的虚拟 .asmx webservice。

请让我知道或建议我如何即时创建并使用虚拟服务。

【问题讨论】:

  • 您应该查看mocking。那里有numerous frameworks
  • 如果您正在调用服务,那么您没有执行单元测试。那是一个功能测试,或者可能是一个集成测试。你到底想测试什么?

标签: c# asp.net .net web-services unit-testing


【解决方案1】:

据我所知,有两种不同的功能主义者:

WSDL 提供者 - 即从某处获取有效 wsdl 的类 WSDL 解析器 - 解析 wsdl 并提取数据的类

这里是这些的伪代码实现,使它们易于模拟和单元测试。

public interface IWSDLProvider
{
   string GetWsdlFromService(string url);
}

public class MyWsdlProvider : IWSDLProvider
{
   private readonly IWebWrapper _webCLient;

   public MyWsdlProvider(IwebWrapper webClient)
   {
       _webClient = webCLient;
   }

   public string GetWsdlFromService(string url)
   {
      //do here whatever is needed with the webClient to get the wsdl
   }
}

public interface IWSDLParser
{
   MyServiceData GetServiceDataFromUrl(string url);
}

public class MyWsdlParser : IWSDLParser
{
   private readonly IWSDLProvider _wsdlProvider;
   public MyWsdlParser(IWSDLProvider wsdlProvider)
   {
      _wsdlProvider = wsdlProvider;
   }

   public MyServiceData GetServiceDataFromUrl(string url)
   {
      //use the wsdl provder to fetch the wsdl
      //and then parse it
   }
}

The IWebClient is a wrapper around WebClient to allow easy mocking.

使用带有上述代码的任何模拟框架,您可以轻松地隔离和模拟任何部分,并且只测试手头的行为。这样,您甚至可以为 wsdl 提供者制作模拟,以返回您想要测试的任何 wsdl。

您可以更进一步,包装/隔离 System.Web.Services.ServiceDescription 调用,因此您甚至不必在测试中通过 wsdl,只需处理结果即可。

【讨论】:

    猜你喜欢
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多