代码之家  ›  专栏  ›  技术社区  ›  Tabrock

模拟响应有效,但验证失败

  •  1
  • Tabrock  · 技术社区  · 6 年前

    我正在尝试使用moq模拟单元测试中的HTTP响应。我的模型设置如下:

    var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
    
    mockHandler
        .Protected()
        // Sets up mock for the protected SendAsync method
        .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
        // Prepare the expected response of the mocked HTTP call
        .ReturnsAsync(new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent("{\"stuff\":[\""+expectedstuff+"\"]}"), })
        .Verifiable();
    

    然后我创建httpclient:

    var client = new HttpClient(mockHandler.Object)
    {
        BaseAddress = new Uri(expectedRequestUri),
    };
    

    然后我将邮件发送给客户:

    var response = await client.PostAsync("/path", new StringContent(""));
    

    当我反序列化响应时,它与我在上面的设置步骤中设置的模拟响应完全匹配,并且一切看起来都很好。但是,在最后一步中,我遇到了一个引发异常的问题(下面)。

    mockHandler
        .Protected()
        .Verify(
            "SendAsync",
            Times.Exactly(1),
            ItExpr.Is<HttpRequestMessage>(request => request.Method == HttpMethod.Post && request.RequestUri == new Uri(expectedRequestUri)),
            ItExpr.IsAny<CancellationToken>());
    

    错误:

    moq.mockexception:对mock的预期调用正好是1次,但却是0次: mock => mock.SendAsync(It.Is<HttpRequestMessage>(request => request.Method == HttpMethod.Post && request.RequestUri == new Uri(.expectedRequestUri)), It.IsAny<CancellationToken>())

    我不知道为什么它报告了0次,因为我得到的响应与模拟的响应匹配,所以它看起来正常工作。任何来自社区的想法都是有益的。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Nkosi    6 年前

    在这种情况下,您必须检查 Verify .

    它显然与调用的内容不匹配。

    如果客户端的基地址是 expectedRequestUri

    var client = new HttpClient(mockHandler.Object)
    {
        BaseAddress = new Uri(expectedRequestUri), //<--
    };
    

    这篇文章是用 /path

    var response = await client.PostAsync("/path", new StringContent("")); //<--
    

    那么请求URL将是这两者的组合。

    但是在你检查的验证中

    request.RequestUri == new Uri(expectedRequestUri)