我在尝试使用Moq和RestSharp时遇到了一些挑战。也许这是我对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;
}
}
由于某种原因,响应对象为null。可能是我错误地嘲笑返回对象吗?
答案 0 :(得分:10)
出于披露目的,我假设您的IncidentRestClient有一个构造函数,该构造函数将 IRestClient 实例作为参数并使用它来设置客户端成员。
在您的测试中,您似乎正在运行安装程序以执行与您正在使用的Execute不同的重载。而不是:
.Setup(x => x.Execute(
尝试:
.Setup(x => x.Execute<RootObjectList>(