1

I have the following method to create a Http client with a mocked response:

public static HttpClient GetMockedHttpClient(string responseContent, HttpStatusCode httpStatusCode)
        {
            var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
            handlerMock
               .Protected()
               .Setup<Task<HttpResponseMessage>>(
                  "SendAsync",
                  ItExpr.IsAny<HttpRequestMessage>(),
                  ItExpr.IsAny<CancellationToken>()
               )
               .ReturnsAsync(new HttpResponseMessage()
               {
                   StatusCode = httpStatusCode,
                   Content = new StringContent(responseContent),
               })
               .Verifiable();
            return new HttpClient(handlerMock.Object);
        }

How can I make the response dependent on a specific url, so that the setup only takes effect when the HttpClient is called with a given address?

DaveVentura
  • 612
  • 5
  • 19
  • 1
    related: https://stackoverflow.com/questions/37051371/why-use-it-is-or-it-isany-if-i-could-just-define-a-variable (difference between `IsAny()` and `Is()`) – Andrew Oct 15 '21 at 15:23

2 Answers2

3

What you need to change is the line:

ItExpr.IsAny<HttpRequestMessage>(),

IsAny<HttpRequestMessage>() means the mock will catch any property of that type, if you want it to catch a specific uri you use Is<HttpRequestMessage>()

ItExpr.Is<HttpRequestMessage>(m => m.RequestUri == [your uri goes here]),
Andrew
  • 1,544
  • 1
  • 18
  • 36
1

I would suggest using https://github.com/justeat/httpclient-interception. I had to run similar tests and it did the job, although I used it to mock whole client.

quain
  • 861
  • 5
  • 18