I am trying to use Moq to mock an HTTP response in a unit test. I've set up my mock like below:
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict); mockHandler .Protected() // Sets up mock for the protected SendAsync method .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) // Prepare the expected response of the mocked HTTP call .ReturnsAsync(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent("{\"stuff\":[\""+expectedstuff+"\"]}"), }) .Verifiable(); I then create the httpclient:
var client = new HttpClient(mockHandler.Object) { BaseAddress = new Uri(expectedRequestUri), }; I then post to the client:
var response = await client.PostAsync("/path", new StringContent("")); When I deserialize the response, it matches the mocked response I set up in the Setup step above exactly, and everything appears fine. However, in the last step I encounter an issue which throws an exception (below)...
mockHandler .Protected() .Verify( "SendAsync", Times.Exactly(1), ItExpr.Is<HttpRequestMessage>(request => request.Method == HttpMethod.Post && request.RequestUri == new Uri(expectedRequestUri)), ItExpr.IsAny<CancellationToken>()); Error:
Moq.MockException: Expected invocation on the mock exactly 1 times, but was 0 times:
mock => mock.SendAsync(It.Is<HttpRequestMessage>(request => request.Method == HttpMethod.Post && request.RequestUri == new Uri(.expectedRequestUri)), It.IsAny<CancellationToken>())
I have no clue why it's reporting 0 times, as the response I get matches the mocked response so it appears to be functioning. Any thoughts from the community would be helpful.
expectedRequestUribut the Post is done with/paththen the request url would be a combining of the two.