首页 > 解决方案 > 根据请求 URL c# 模拟 HttpMessageHandler

问题描述

我有以下方法来创建一个带有模拟响应的 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 时生效?

标签: c#unit-testingmockingmoq

解决方案


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


推荐阅读