如何在单元测试中模拟RestSharp可移植库

时间:2017-03-07 11:14:06

标签: c# unit-testing xamarin moq restsharp

我想为测试目的模拟RestClient类

public class DataServices : IDataServices
{
    private readonly IRestClient _restClient;


    public DataServices(IRestClient restClient)
    {
        _restClient = restClient;
    }

    public async Task<User> GetUserByUserName(string userName)
    {
        User user = null;

        // create a new request
        var restRequest = new RestRequest("User", Method.GET);
        // create REST parameters
        restRequest.AddParameter("userName", userName, ParameterType.QueryString);
        // execute the REST request
        var restResponse = await _restClient.Execute<User>(restRequest);
        if (restResponse.StatusCode.Equals(HttpStatusCode.OK))
        {
            user = restResponse.Data;
        }
        return user;
    }

}

我的测试班:

[TestClass]
public class DataServicesTest
{
    public static IRestClient MockRestClient<T>(HttpStatusCode httpStatusCode, string json)
    {
        var mockIRestClient = new Mock<IRestClient>();
        mockIRestClient.Setup(x => x.Execute<T>(It.IsAny<IRestRequest>()))
          .Returns(new RestResponse<T>
          {
              Data = JsonConvert.DeserializeObject<T>(json),
              StatusCode = httpStatusCode
          });
        return mockIRestClient.Object;
    }

    [TestMethod]
    public async void GetUserByUserName()
    {
        var dataServices = new DataServices(MockRestClient<User>(HttpStatusCode.OK, "my json code"));
        var user = await dataServices.GetUserByUserName("User1");
        Assert.AreEqual("User1", user.Username);
    }
}

但我无法实例化RestResponse对象,我发现以下错误:

.Returns(new RestResponse<T>
{
    Data = JsonConvert.DeserializeObject<T>(json),
    StatusCode = httpStatusCode
});
  

无法访问受保护的内部构造函数&#39; RestResponse&#39;这里。

我该如何解决这个问题?我在Xamarin便携式库上使用FubarCoder.RestSharp nuget包。

2 个答案:

答案 0 :(得分:7)

模拟IRestResponse<T>并返回

public static IRestClient MockRestClient<T>(HttpStatusCode httpStatusCode, string json) 
    where T : new() {
    var data = JsonConvert.DeserializeObject<T>(json)
    var response =  new Mock<IRestResponse<T>>();
    response.Setup(_ => _.StatusCode).Returns(httpStatusCode);
    response.Setup(_ => _.Data).Returns(data);

    var mockIRestClient = new Mock<IRestClient>();
    mockIRestClient
      .Setup(x => x.Execute<T>(It.IsAny<IRestRequest>()))
      .ReturnsAsync(response.Object);
    return mockIRestClient.Object;
}

测试也应该更新为异步

[TestMethod]
public async Task GetUserByUserName() {
    //Arrange
    var client = MockRestClient<User>(HttpStatusCode.OK, "my json code");
    var dataServices = new DataServices(client);
    //Act
    var user = await dataServices.GetUserByUserName("User1");
    //Assert
    Assert.AreEqual("User1", user.Username);
}

答案 1 :(得分:1)

我没有找到任何好的答案,所以我最终编写了一个帮助库。我将它发布到 NuGet - MoqRestSharp.Helpers。该项目旨在帮助对 RestSharp 进行单元测试,因为它扩展了 Mock,因此这有助于我测试我的 RestSharp 请求和响应错误处理。

它使用最小起订量

随时欢迎反馈!