3

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?

3

1 Answer 1

6

There's no PostAsync method on the handler.

You need to mock SendAsync(HttpRequestMessage, CancellationToken)

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

Comments

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.