2015-05-11 107 views
3

我在嘗試使用Moq和RestSharp時遇到了一些挑戰。也許這是我對Moq的誤解,但是由於某種原因,我試圖模擬一個RestResponse的時候,我總是得到一個空引用異常。RestSharp單元測試NUnit Moq RestResponse空引用異常

這是我的單元測試。

[Test] 
    public void GetAll_Method_Throws_exception_if_response_Data_is_Null() 
    { 
     var restClient = new Mock<IRestClient>(); 

     restClient.Setup(x => x.Execute(It.IsAny<IRestRequest>())) 
      .Returns(new RestResponse<RootObjectList> 
      { 
       StatusCode = HttpStatusCode.OK, 
       Content = null 
      }); 

     var client = new IncidentRestClient(restClient.Object); 

     Assert.Throws<Exception>(() => client.GetAll()); 
    } 

這是我真正的實現:

public class IncidentRestClient : IIncidentRestClient 
{ 
    private readonly IRestClient client; 
    private readonly string url = "some url here"; 

    public IncidentRestClient() 
    { 
     client = new RestClient { BaseUrl = new Uri(url) }; 
    } 

    public RootObjectList GetAll() 
    { 
     var request = new RestRequest("api/now/table/incident", Method.GET) { RequestFormat = DataFormat.Json }; 
     request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; 

     IRestResponse<RootObjectList> response = client.Execute<RootObjectList>(request); 

     if (response.Data == null) 
      throw new Exception(response.ErrorException.ToString()); 

     return response.Data; 
    } 
} 

出於某種原因,響應對象爲空。難道是我嘲笑錯誤地返回對象?

+0

什麼是 「?IncidentRestClient」它是你定義的類型嗎? –

+0

嗨,肖恩。是的,這是我定義的類型..請參閱上面的修改。 – jaypman

+0

它看起來像你的'IncidentRestClient'的構造函數不會把'IRestClient'作爲參數。是否有另一個構造函數定義了該參數? –

回答

9

。爲了公開的目的,我假設你IncidentRestClient有一個構造函數的IRestClient實例作爲參數,並使用它來設置客戶成員。

看起來,在您的測試中,您正在爲執行的不同重載運行安裝程序,而不是您正在使用的那個。相反的:

.Setup(x => x.Execute(

嘗試:

.Setup(x => x.Execute<RootObjectList>(
+0

嗨,肖恩。非常感謝!! :)我不敢相信我忽略了安裝過程中的這種過載。我現在得到一個RestReponse對象。 – jaypman

+0

是的,它具有公共IncidentRestClient(IRestClient客戶端)的構造函數 this.client = client; } – jaypman

+2

@jaypman你應該接受這個答案,如果它是正確的/有幫助的。 upvote會很好。這是如何工作的。 –