在同一个方法中模拟许多 httpClient 调用

Mock many httpClient calls in the same method

我正在尝试使用 Moq 和 xunit 编写单元测试。在此测试中,我必须模拟两个 httpClient 调用。

我正在为 dotnetcore 编写单元测试 API。 在我的 API 中,我必须对另一个 API 进行 2 次 HTTP 调用才能获得我想要的信息。 - 在第一次调用中,我从这个 API 获得了一个 jwt 令牌。 - 在第二次调用中,我使用我在第一次调用中 getter 获取我需要的信息的令牌进行了 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();

这将允许您定义一个模拟 returns 两个不同的值,具体取决于输入的 HttpRequestMethod.RequestUri.Path 属性.