c# - 根据请求 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 时生效?
解决方案
我建议使用https://github.com/justeat/httpclient-interception。我必须运行类似的测试并且它完成了这项工作,尽管我用它来模拟整个客户端。
推荐阅读
- css - 使用 flexbox 水平方向弄乱了我的对齐方式
- python - 线性回归中代价函数的实现
- javascript - JS从blob中获取字符串
- javascript - 使用原生选择与 antd
- python - 将 QDataStream 对象传递给另一个方法(复制构造函数与有状态)
- php - PHP xammp sendmail 错误:邮件缺少发件人地址
- python - 我应该在 Python 中使用 JSON.dumpS 和 .write() 函数还是 json.dump()
- python - 如何迭代直到在python for循环中满足条件
- python - 线性模型: numpy.ndarray 大小已更改,可能表示二进制不兼容。预期来自 C 标头的 88,从 PyObject 得到 80”
- react-native - 基于游标的分页无限调用查询