如何从程序集中获取.NET生成的WSDL文件?

时间:2013-10-02 18:54:09

标签: asp.net web-services unit-testing wsdl

我有一个ASP.NET Web服务,我正在尝试编写单元测试。我需要测试的一件事是,从Web服务生成的WSDL文件符合某些标准。但是,我无法弄清楚如何在不实际向Web服务发出HTTP请求的情况下获取WSDL文件。

喜欢做的事情是这样的(伪代码):

using System.Web;
using System.Web.Services;

[WebService]    
class MyWebService : System.Web.Services.WebService
{
    [WebMethod]
    string PopNextItem()
    {
        // Retrieve a string from the database and then delete that record.
    }
}

(剪断)

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
class WebServiceTest
{
    bool CheckWSDLMeetsCriteria(string WSDL)
    {
        bool success = true;
        // Check file here
        return success;
    }

    [TestMethod]
    void WSDL_Should_Match_Criteria()
    {
        string generatedWSDL = getWSDL(MyWebService.PopNextItem);
        Assert.IsTrue(CheckWSDLMeetsCriteria(generatedWSDL));
    }
}

当然,没有getWSDL方法,我不知道怎么写一个。我想我可以从测试中调用wsdl.exe然后获取输出文件,但我希望有更好的方法。 .NET是否提供了以编程方式生成WSDL文件的任何方法?

如果不这样做,我想我可以尝试使用对IIS的HTTP请求来检索WSDL文件。问题是,当在本地计算机上运行单元测试时,IIS的本地实例可能不会运行。尝试从登台服务器或类似的东西获取WSDL文件会导致可能针对旧版本的服务进行测试(本地计算机上的Web服务代码可能在登台服务器更新后可能已更改),或者更糟糕的是我可能没有互联网接入,无法测试。

我很好奇别人会推荐什么解决方案。你觉得怎么样?

1 个答案:

答案 0 :(得分:1)

到目前为止,我找到了两种可能的选项。

A. 使用ServiceDescriptionReflector生成WSDL文件。 [Source]

ServiceDescriptionReflector reflector = new ServiceDescriptionReflector(); 
reflector.Reflect(typeof(MyService), "http://localhost/vdir/Foo.asmx");

if (reflector.ServiceDescriptions.Count > 1){
  throw new Exception("Deal with multiple service descriptions later");
}

XmlTextWriter wtr = new XmlTextWriter(Console.Out); 
wtr.Formatting = Formatting.Indented; 
reflector.ServiceDescriptions[0].Write(wtr); 
wtr.Close();

B。 Use Svcutil.exe to Export Metadata from Compiled Service Code [Source]