1

I have a service method that does a request using HttpClient. The service class constructor injects IHttpClientFactory and creates the client using this code:

_httpClient = httpClientFactory.CreateClient(url);

In my test constructor I am trying to mock the PostAsync method response.

public MyServiceUnitTests()
    {
        _HttpClientMock = new Mock<IHttpClientFactory>();
        var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
        mockHttpMessageHandler.Protected()
            .Setup<Task<HttpResponseMessage>>("PostAsync", ItExpr.IsAny<string>(), ItExpr.IsAny<HttpContent>())
            .ReturnsAsync(new HttpResponseMessage{ StatusCode = HttpStatusCode.OK });
        var httpClient = new HttpClient(mockHttpMessageHandler.Object);
        _HttpClientMock.Setup(x => x.CreateClient(It.IsAny<string>())).Returns(httpClient);

        _Service = new MyService(_HttpClientMock.Object);
    }

I am getting the following error when setting up the mockHttpMessageHandler: System.ArgumentException: 'No protected method HttpMessageHandler.PostAsync found whose signature is compatible with the provided arguments (string, HttpContent).'

What am I doing wrong?

sebastian.roibu
  • 2,579
  • 7
  • 37
  • 59
  • You can check similar implementation in the rated answer https://stackoverflow.com/questions/36425008/mocking-httpclient-in-unit-tests – ivan_k Apr 10 '21 at 16:22
  • Does this answer your question? [Mocking HttpMessageHandler with moq - How do I get the contents of the request?](https://stackoverflow.com/questions/65413738/mocking-httpmessagehandler-with-moq-how-do-i-get-the-contents-of-the-request) – Peter Csala Apr 12 '21 at 08:59
  • Please also check [this article](https://hamidmosalla.com/2017/02/08/mock-httpclient-using-httpmessagehandler/) – Peter Csala Apr 12 '21 at 08:59

1 Answers1

5

There's no PostAsync method on the handler.

You need to mock SendAsync(HttpRequestMessage, CancellationToken)

ESG
  • 8,988
  • 3
  • 35
  • 52