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?
CodePudding user response:
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]),
CodePudding user response:
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.