C# RestSharp单元测试NUnit Moq重新响应空引用异常
我在尝试使用RestSharp的Moq时遇到了一些挑战。也许这是我对Moq的误解,但出于某种原因,我在试图模拟RestResponse时不断得到一个空引用异常 这是我的单元测试C# RestSharp单元测试NUnit Moq重新响应空引用异常,c#,moq,restsharp,C#,Moq,Restsharp,我在尝试使用RestSharp的Moq时遇到了一些挑战。也许这是我对Moq的误解,但出于某种原因,我在试图模拟RestResponse时不断得到一个空引用异常 这是我的单元测试 [Test] public void GetAll_Method_Throws_exception_if_response_Data_is_Null() { var restClient = new Mock<IRestClient>(); restC
[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 void GetAll方法如果响应数据为Null()则抛出异常
{
var restClient=new Mock();
restClient.Setup(x=>x.Execute(It.IsAny()))
.返回(新的重新响应)
{
StatusCode=HttpStatusCode.OK,
内容=空
} );
var client=newincidentrestclient(restClient.Object);
Assert.Throws(()=>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:IIIncidentRestClient
{
私有只读IRestClient客户端;
私有只读字符串url=“此处的某些url”;
公共事件客户机()
{
client=newrestclient{BaseUrl=newuri(url)};
}
公共RootObjectList GetAll()
{
var request=new RestRequest(“api/now/table/incident”,Method.GET){RequestFormat=DataFormat.Json};
request.OnBeforeDeserialization=resp=>{resp.ContentType=“application/json”;};
IRestResponse response=client.Execute(请求);
if(response.Data==null)
抛出新异常(response.ErrorException.ToString());
返回响应数据;
}
}
由于某些原因,响应对象为null。可能是我错误地模拟了返回对象吗?出于公开目的,我假设您的IncidentRestClient有一个构造函数,该构造函数将IRestClient实例作为参数,并使用它设置客户端成员 看起来,在测试中,您运行的安装程序的Execute重载与您使用的不同。而不是:
.Setup(x => x.Execute(
尝试:
.Setup(x=>x.Execute(
什么是“IncidentRestClient?”这是您定义的类型吗?Hi Sean.是的,这是我定义的类型..请参见上面的编辑。您的IncidentRestClient
的构造函数似乎没有将IRestClient
作为参数。是否定义了另一个构造函数来接受该参数?Hi Sean.非常感谢!!:)我不敢相信我在安装中忽略了这个重载。我现在得到了一个RestReponse对象。是的,它有constructor public IncidentRestClient(IRestClient client){this.client=client;}@jaypman如果回答正确/有用,你应该接受这个答案。向上投票会很好。这就是它的工作原理。@ToddMenier我现在不能向上投票b/c它说我至少需要15个声誉点。
.Setup(x => x.Execute<RootObjectList>(