RestSharp Unit Test NUnit Moq RestResponse null reference exception
我在尝试将 Moq 与 RestSharp 结合使用时遇到了一些挑战。也许这是我对 Moq 的误解,但由于某种原因,我在尝试模拟 RestResponse 时不断收到空引用异常。
这是我的单元测试。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | [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()); } |
这是我的实际实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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 有一个构造函数,该构造函数将 IRestClient 实例作为参数并使用它来设置客户端成员。
看起来,在您的测试中,您正在运行安装程序的 Execute 重载与您正在使用的重载不同。而不是:
1 | .Setup(x => x.Execute( |
尝试:
1 | .Setup(x => x.Execute<RootObjectList>( |