.net-core - 在同一方法中模拟许多 httpClient 调用
问题描述
我正在尝试使用 Moq 和 xunit 编写单元测试。在这个测试中,我必须模拟两个 httpClient 调用。
我正在为 dotnetcore API 编写单元测试。在我的 API 中,我必须对另一个 API 进行 2 次 HTTP 调用才能获得我想要的信息。- 在第一次调用中,我从这个 API 获得了一个 jwt 令牌。- 在第二次调用中,我使用在第一次调用中获取的令牌进行了 GetAsync 调用,以获取我需要的信息。
我不知道如何模拟这两个不同的调用。在这段代码中,我只能模拟一个 httpClient 调用
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
.Protected()
// Setup the PROTECTED method to mock
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
// prepare the expected response of the mocked http call
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.BadRequest,
Content = new StringContent(JsonConvert.SerializeObject(getEnvelopeInformationsResponse), Encoding.UTF8, "application/json")
})
.Verifiable();
你知道我该怎么做才能获得两个不同的调用并获得两个不同的 HttpResponseMessage 吗?
解决方案
不要使用It.IsAny
和使用It.Is
。
该It.Is
方法将允许您指定谓词以查看参数是否匹配。
在您的示例中:
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
It.Is<HttpRequestMessage>(x => x.RequestUri.Path == "/myjwtpath"),
It.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage(...))
.Verifiable();
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
It.Is<HttpRequestMessage>(x => x.RequestUri.Path == "/myotherpath"),
It.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage(...))
.Verifiable();
这将允许您定义一个模拟,该模拟根据输入的HttpRequestMethod.RequestUri.Path
属性返回两个不同的值。
推荐阅读
- pytorch - 组装需要渐变的 PyTorch `Tensor` 的有效方法
- c++ - 在 Windows 10 Visual Studio 2017 上为 FTPS 设置 Curl
- maven - 从 Maven 存储库中获取最新版本
- javascript - 如何检查表的父类
- gdb - GDB“服务器”命令
- plone - 自定义用户偏好存储
- opendaylight - 使用 Yangtools 无法从 yang 文件生成 Pojos
- javascript - 我想用 server.js 中 req.body 的新数据填充employeeData
- arrays - swift reversed的时间复杂度是多少?
- macos - 无法导入证书以登录钥匙串 (OS X 10.13.5)