在.NET中测试缺少必填字段的Web服务
问题描述:
我当前工作的一部分涉及使用外部Web服务,为此我生成了客户端代理代码(使用WSDL.exe工具)。在.NET中测试缺少必填字段的Web服务
我需要测试Web服务是否正确处理缺少必填字段。例如,Surname和Forename是强制性的 - 如果它们不在调用中,那么应该返回一个SOAP错误块。
正如您可能已经猜到的那样,在使用自动生成的代理代码时,由于对模式进行编译时检查,我无法排除Web服务调用中的任何必填字段。
我所做的是使用HttpWebRequest和HttpWebResponse将手动格式的SOAP信封发送/接收到Web服务。这是有效的,但是因为服务返回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
答
什么编写你自己的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];
}
}
非常感谢您的回答,Ishtar。不幸的是,这对我并不适用 - 在幕后,Invoke()尝试将对象参数序列化为由wsdl.exe工具生成的匹配强类型。 如果我错过了一个参数,将其设置为空字符串,或将其设置为空,我得到一个XmlSerializer异常,并且Web服务不会被调用:( – 2009-05-13 11:43:53