简体   繁体   中英

Mock HttpClient.SendAsync to return response with Content not null

I'm trying to mock var response = await httpClient.SendAsync(request, CancellationToken.None); but my response.Content is always null .

My mock looks like...

var httpResponseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
httpResponseMessage.Content = new StringContent("test content", System.Text.Encoding.UTF8, "application/json");
A.CallTo(() => httpClient.SendAsync(A.Fake<HttpRequestMessage>(), CancellationToken.None)).Returns(Task.FromResult(httpResponseMessage));

it seems like it is properly mocked but the response.Content is null but the status code - for example - reflects what I set in the test.

I'm sure one of you guys out here have encountered this problem, all help will be greatly appreciated. Thanks.

Likely the call to SendAsync isn't being matched. I see you configured your fake to respond to

A.CallTo(() => httpClient.SendAsync(A.Fake<HttpRequestMessage>(), CancellationToken.None))

But it's very unlikely that your production code is passing a first argument that compares as equal to the A.Fake<HttpRequestMessage>() argument you have here.

Did you instead mean

A.CallTo(() => httpClient.SendAsync(A<HttpRequestMessage>.Ignored, CancellationToken.None))

(or equivalently A<HttpRequestMessage>._ )?

You can read about how arguments are matched on the Argument constraints page. Specifically, see how to match any argument at the Ignoring arguments subtopic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM