首页 > 解决方案 > 在同一方法中模拟许多 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 吗?

标签: .net-corehttpclientmoq

解决方案


不要使用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属性返回两个不同的值。


推荐阅读