I am writing test cases using xUnit and Moq.
I am trying to mock PostAsync() of HttpClient, but I get an error.
Below is the code used for mocking:
public TestADLS_Operations()
{
var mockClient = new Mock<HttpClient>();
mockClient.Setup(repo => repo.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>())).Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
this._iADLS_Operations = new ADLS_Operations(mockClient.Object);
}
Error:
Unsupported expression: repo => repo.PostAsync(It.IsAny(),
It.IsAny()) Non-overridable members (here:
HttpClient.PostAsync) may not be used in setup / verification
expressions.
Screenshot:
Best Answer
I also tried to mock the
HttpClient
the same way you did, and I got the same error message.Solution:
Instead of mocking the
HttpClient
, mock theHttpMessageHandler
.Then give the
mockHttpMessageHandler.Object
to yourHttpClient
, which you then pass to your product code class. This works becauseHttpClient
usesHttpMessageHandler
under the hood:Note: You will also need a
at the top of your test file.
Then you can call your method that uses
PostAsync
from your test, andPostAsync
will return an HTTP status OK response:Advantage: Mocking
HttpMessageHandler
means that you don't need extra classes in your product code or your test code.Helpful resources: