Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock RestSharp portable library in Unit Test

I would like to mockup the RestClient class for test purposes

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;
    }

}

My test class :

[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);
    }
}

But I can't instantiate the RestResponse object, I've the following error:

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

Cannot access protected internal constructor 'RestResponse' here.

How can I workaround this ? I'm using the FubarCoder.RestSharp nuget package on a Xamarin portable Library.

like image 340
Florian SANTI Avatar asked Mar 07 '17 11:03

Florian SANTI


People also ask

Is RestSharp better than HttpClient?

The main conclusion is that one is not better than the other, and we shouldn't compare them since RestSharp is a wrapper around HttpClient. The decision between using one of the two tools depends on the use case and the situation.

What is RestSharp library?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.


1 Answers

Mock IRestResponse<T> and return that

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;
}

The test should also be updated to be async as well

[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);
}
like image 181
Nkosi Avatar answered Sep 20 '22 05:09

Nkosi