2

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.

2
  • check the expression used in the verify. It apparently does not match what was invoked. Commented Feb 7, 2019 at 22:17
  • If the base is expectedRequestUri but the Post is done with /path then the request url would be a combining of the two. Commented Feb 7, 2019 at 22:20

1 Answer 1

2

In situations like this you have to check the expression used in the Verify.

It apparently does not match what was invoked.

If the base address of the client is expectedRequestUri

var client = new HttpClient(mockHandler.Object) { BaseAddress = new Uri(expectedRequestUri), //<-- }; 

and the Post is done with /path

var response = await client.PostAsync("/path", new StringContent("")); //<-- 

then the request url would be a combining of the two.

But in the verify you check

request.RequestUri == new Uri(expectedRequestUri) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.