How to create mock for httpclient getasync method?

三世轮回 提交于 2020-07-21 12:54:25

问题


I am using Moq to create mocks for my unit tests but I am stuck when I have to create mock for getasync method of httpclient. Previously I was using SendAsync method and for that I could use the below code:

   var mockResponse =
            new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(expectedResponse)};
        mockResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var mockHandler = new Mock<DelegatingHandler>();
        mockHandler
            .Protected()
            .Setup<Task<HttpResponseMessage>>(
                "SendAsync",
                ItExpr.Is<HttpRequestMessage>(
                    message => message.Headers.Contains("Authorization")
                               && message.Headers.Authorization.Parameter.Equals(accessToken)
                               && message.Headers.Authorization.Scheme.Equals("Bearer")
                               && message.RequestUri.AbsoluteUri.Contains(baseUrl)
                ),
                ItExpr.IsAny<CancellationToken>())
            .Returns(Task.FromResult(mockResponse));

Now I have a method:

  private async Task<List<Model>> GetData()
  {
        string url = url;
        _httpClient.BaseAddress = new Uri(url);
        _httpClient.DefaultRequestHeaders.Add(Headers.AuthorizationHeader, "Bearer" + "token");
        var response = await _httpClient.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsAsync<List<Model>>();
  }

Now can I create mock for this method (getasync)? Any help?


回答1:


Internally GetAsync will eventually call SendAsync.

public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption,
    CancellationToken cancellationToken)
{
    return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}

Source code

Loosen the ItExpr expectation and you should be able to get it to behave as expected.

Using the originally provided example

mockHandler
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
        "SendAsync",
        ItExpr.IsAny<HttpRequestMessage>(),
        ItExpr.IsAny<CancellationToken>()
    )
    .ReturnsAsync(mockResponse);


来源:https://stackoverflow.com/questions/53081733/how-to-create-mock-for-httpclient-getasync-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!