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.

Robert Green MBA
  • 1,834
  • 1
  • 22
  • 45
  • 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 – Camilo Terevinto Jan 01 '21 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. https://github.com/WireMock-Net/WireMock.Net – silkfire Jan 02 '21 at 02:08

1 Answers1

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.

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111