sebastian.roibu
sebastian.roibu

Reputation: 2859

Net Core testing method with HttpClient

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?

Upvotes: 3

Views: 2226

Answers (1)

ESG
ESG

Reputation: 9425

There's no PostAsync method on the handler.

You need to mock SendAsync(HttpRequestMessage, CancellationToken)

Upvotes: 6

Related Questions