问题
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