根据请求模拟 HttpMessageHandler Url c#

Mocking HttpMessageHandler depending on the Request Url c#

我有以下方法来创建带有模拟响应的 Http 客户端:

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);
        }

如何使响应依赖于特定的 url,以便设置仅在使用给定地址调用 HttpClient 时生效?

您需要更改的是行:

ItExpr.IsAny<HttpRequestMessage>(),

IsAny<HttpRequestMessage>() 表示模拟将捕获该类型的任何 属性,如果您希望它捕获您使用的特定 uri Is<HttpRequestMessage>()

ItExpr.Is<HttpRequestMessage>(m => m.RequestUri == [your uri goes here]),

我建议使用 https://github.com/justeat/httpclient-interception。 我不得不 运行 进行类似的测试并且它完成了工作,尽管我用它来模拟整个客户端。