2015-02-05 72 views
0

我需要爲WCF Rest服務編寫一個單元測試。 這是方法之一:如何寫一個單元測試WCF Rest服務

接口:

[OperationContract] 
    [WebInvoke(Method = "GET", 

           ResponseFormat = WebMessageFormat.Json, 
           BodyStyle = WebMessageBodyStyle.Bare, 

           UriTemplate = "CustomerProfile")] 
    Model.Customer CustomerProfile(); 

實現:

public Model.Customer CustomerProfile() 
    { 
     return GetCustomerInfo.Instance.returnCustomerProfile(); 
    } 

returnCustomerProfile方法會調用數據庫,並返回客戶信息。

在單元測試項目中,我添加了服務URL。我不知道如何繼續。如果你有任何網站或樣本會幫助很多。

 [TestMethod] 
    public void TestUpdatePasswordWeb() 
    { 
    string strServiceUrl = "http://localhost:64440/CustomerRestService.svc/UpdatePassword"; 

.... 

    } 

回答

0

你在寫什麼不是單元測試,它是一個集成測試。 爲了編寫單元測試,您需要能夠將您的課程與其他課程分開,並且只測試其功能。 這意味着你不應該使用:

return GetCustomerInfo.Instance.returnCustomerProfile(); 

GetCustomerInfo.Instance是(我認爲)通過靜態類的getCustomerInfo,因此很難嘲笑訪問的單身。你應該「注入」GetCustomerInfo.Instance到你的類中,以便能夠模擬它進行單元測試。

我鼓勵您將依賴注入庫合併到您的項目中,並將模擬庫合併到您的單元測試中。

除非您需要使用WCF REST服務,否則我還鼓勵您使用MVC Web API來滿足您的REST需求。它具有爲REST構建的目的,並且不會受到WCF的一切和接收方式的影響。