How to mock RestSharp portable library in Unit Test

前端 未结 1 1795
旧巷少年郎
旧巷少年郎 2021-02-05 20:44

I would like to mockup the RestClient class for test purposes

public class DataServices : IDataServices
{
    private readonly IRestClient _restClient;


    pub         


        
相关标签:
1条回答
  • 2021-02-05 21:27

    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);
    }
    
    0 讨论(0)
提交回复
热议问题