0

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.

2
  • Because that's not a valid HttpResponseMessage. It's missing some headers if not something else too. Why don't you just create a mock DelegatingHandler class? It's the simplest way IMHO Commented Jan 1, 2021 at 22:54
  • There's a really good library out there created specifically to simplify mocking of the HttpClient. It's called WireMock, you should give it a try. github.com/WireMock-Net/WireMock.Net Commented Jan 2, 2021 at 2:08

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that's exactly what I forgot .Ignored

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.