【发布时间】: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