【问题标题】:Mock many httpClient calls in the same method在同一方法中模拟许多 httpClient 调用
【发布时间】:2019-05-10 11:35:16
【问题描述】:

我正在尝试使用 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-core httpclient moq


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2017-06-25
      • 2021-11-04
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多