我在嘗試使用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;
}
}
出於某種原因,響應對象爲空。難道是我嘲笑錯誤地返回對象?
什麼是 「?IncidentRestClient」它是你定義的類型嗎? –
嗨,肖恩。是的,這是我定義的類型..請參閱上面的修改。 – jaypman
它看起來像你的'IncidentRestClient'的構造函數不會把'IRestClient'作爲參數。是否有另一個構造函數定義了該參數? –