模拟响应有效但验证失败

Mock responses are working but verification fails

我正在尝试使用 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),
};

然后我post给客户:

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: Expected invocation on the mock exactly 1 times, but was 0 times: mock => mock.SendAsync(It.Is<HttpRequestMessage>(request => request.Method == HttpMethod.Post && request.RequestUri == new Uri(.expectedRequestUri)), It.IsAny<CancellationToken>())

我不知道为什么它报告 0 次,因为我得到的响应与模拟响应相匹配,所以它似乎在运行。社区的任何想法都会有所帮助。

在这种情况下,您必须检查 Verify 中使用的表达式。

它显然与调用的不匹配。

如果客户端的基地址是expectedRequestUri

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

并且 Post 是用 /path

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

那么请求 url 将是两者的结合。

但是在验证中你检查

request.RequestUri == new Uri(expectedRequestUri)