Reputation: 2859
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
Reputation: 9425
There's no PostAsync
method on the handler.
You need to mock SendAsync(HttpRequestMessage, CancellationToken)
Upvotes: 6