iloveseven
iloveseven

Reputation: 685

Moq, Method HttpClient.SendAsync is public. How to fix?

I am getting the error:

System.ArgumentException: Method HttpClient.SendAsync is public. Use strong-typed Expect overload instead: mock.Setup(x => x.SendAsync());

While trying to run the following code:

autoMock.Mock<HttpClient>()
        .Protected()
        .Setup<Task<HttpResponseMessage>>(
            "SendAsync",
            ItExpr.IsAny<HttpRequestMessage>(),
            ItExpr.IsAny<CancellationToken>()
        )
        .ReturnsAsync(httpResponseMessage)
        .Verifiable();

What may I be missing here?

Upvotes: 2

Views: 2413

Answers (1)

Peter Csala
Peter Csala

Reputation: 22679

  1. you need to mock the HttpRequestHandler:

(You might need to pass MockBehavior.Strict to the Mock<T> ctor)

var mockedHandler = new Mock<HttpMessageHandler>();
  1. you need to create the expected response:
var expectedResponse = new HttpResponseMessage
{
    StatusCode = HttpStatusCode.OK,
    Content = new StringContent(@"..."),
};
  1. you have to wire up things:
mockedHandler
   .Protected()
   .Setup<Task<HttpResponseMessage>>(
      "SendAsync",
      ItExpr.IsAny<HttpRequestMessage>(),
      ItExpr.IsAny<CancellationToken>())
   .ReturnsAsync(expectedResponse);
  1. finally you should pass that mockedHandler when you instantiate the HttpClient instance
var httpClient = new HttpClient(handlerMock.Object);

It is worth to take look at the MockHttp library, it makes your mocking lot easier.

Upvotes: 3

Related Questions