2009-05-12 75 views
1

我當前工作的一部分涉及使用外部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

回答

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]; 
     } 
    } 
+0

非常感謝您的回答,Ishtar。不幸的是,這對我並不適用 - 在幕後,Invoke()嘗試將對象參數序列化爲由wsdl.exe工具生成的匹配強類型。 如果我錯過了一個參數,將其設置爲空字符串,或將其設置爲空,我得到一個XmlSerializer異常,並且Web服務不會被調用:( – 2009-05-13 11:43:53