【问题标题】:Testing a web service for missing mandatory fields in .NET测试 .NET 中缺少必填字段的 Web 服务
【发布时间】:2009-05-12 15:18:17
【问题描述】:

我目前的部分工作涉及使用外部 Web 服务,为此我生成了客户端代理代码(使用 WSDL.exe 工具)。

我需要测试 Web 服务是否正确处理缺少必填字段的情况。例如,姓氏和名字是强制性的 - 如果调用中没有它们,则应返回 SOAP 故障块。

正如您可能已经猜到的那样,在使用自动生成的代理代码时,我无法从我的 Web 服务调用中排除任何必填字段,因为编译时会针对架构进行检查。

我所做的是使用 HttpWebRequest 和 HttpWebResponse 向 Web 服务发送/接收手动格式化的 SOAP 信封。这可行,但由于服务返回 500 HTTP 状态代码,客户端上会引发异常并且响应(包含我需要的 SOAP 故障块)为空。基本上我需要返回流来获取错误数据,这样我才能完成我的单元测试。我知道正在返回正确的数据,因为我可以在我的 Fiddler 跟踪中看到它,但我无法在我的代码中得到它。

这是我为手动调用所做的,更改了名称以保护无辜者:

private INVALID_POST = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<soap:Envelope ...rest of SOAP envelope contents...";

private void DoInvalidRequestTest()
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://myserviceurl.svc");
    request.Method = "POST";
    request.Headers.Add("SOAPAction",
        "\"https://myserviceurl.svc/CreateTestThing\"");
    request.ContentType = "text/xml; charset=utf-8";
    request.ContentLength = INVALID_POST.Length;
    request.KeepAlive = true;

    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(invalidPost);
    }

    try
    {
        // The following line will raise an exception because of the 500 code returned
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        if (response.StatusCode == HttpStatusCode.OK)
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string reply = reader.ReadToEnd();
            }
        }
    }
    catch (Exception ex)
    {
        ... My exception handling code ...
    }
}

请注意,我使用的不是 WCF,而是 WSE 3。

【问题讨论】:

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


    【解决方案1】:

    编写自己的 SoapHttpClientProtocol 并使用 SoapExtensions 怎么样?

        [WebServiceBinding()]
        public class WebService
        : System.Web.Services.Protocols.SoapHttpClientProtocol
        {
            [SoapTrace]
            public object[] MethodTest(string param1, string param2)
            {
                object[] result = this.Invoke("MethodTest", new object[] { param1, param2 });
                return (object[])result[0];
            }
        }
    

    【讨论】:

    • 非常感谢您的回答,伊什塔尔。不幸的是,这对我不起作用——在幕后,Invoke() 尝试将对象参数序列化为由 wsdl.exe 工具生成的匹配强类型。如果我错过了一个参数,将其设置为空字符串,或者将其设置为 null,我会收到 XmlSerializer 异常并且不会调用 Web 服务:(
    猜你喜欢
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多