mock.Verify 受保护的设置的正确语法是什么?

问题描述 投票:0回答:1

我有以下单元测试:

[TestMethod]
public async Task ShouldGetExperimentalValuePost()
{
    //arrange
    var avd = ActualVesselData.Parser.ParseJson(File.ReadAllText(".\\TestFiles\\ActualVesselData-TTN-online.json"));
    const string mlOutputForTestAvd = "{\"timestampAfterEpochMillis\": 1686235071742, \"raw_prediction\": 2.6, \"prediction\": 5.22, \"optimal_prediction\": 5.22, \"version_offline\": 38}";

    var mockMessageHandler = new Mock<HttpMessageHandler>();
    mockMessageHandler.Protected()
        .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
        .ReturnsAsync(new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            Content = new StringContent(mlOutputForTestAvd)
        });

    var mlClient = new MachineLearningClient(
        "http://localhost:7652/predict",
        new HttpClient(mockMessageHandler.Object));

    //act
    var result = await mlClient.DoProcessInput(avd);

    //assert
    Assert.IsNotNull(result, "Did not get a valid response object back from ML module");
    Assert.AreNotEqual((ulong)0, result.Timestamp, "Timestamp missing");
    mockMessageHandler.Protected().Verify("SendAsync()", Times.Once()
    
}

这可以编译,但会出现异常并显示以下消息:

System.ArgumentException:未找到其签名与提供的参数 () 兼容的受保护方法 HttpMessageHandler.SendAsync()。

我尝试了以下方法:

mockMessageHandler.Protected().Verify("SendAsync(ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>)", Times.Once()); 

这给出了同样的例外。

这种情况下正确的语法是什么?

c# asynchronous moq dotnet-httpclient protected
1个回答
0
投票

Verify
中,您应该提供与
Setup

中相同的委托
mockMessageHandler.Protected().Verify(
        "SendAsync",
        Times.Once(),
        ItExpr.IsAny<HttpRequestMessage>(), 
        ItExpr.IsAny<CancellationToken>()
    );

如果您想在断言中包含请求 url,那么您可以执行以下操作

mockMessageHandler.Protected().Verify(
        "SendAsync",
        Times.Once(),
        ItExpr.Is<HttpRequestMessage>(req =>
            req.RequestUri == new Uri("http://localhost:7652/predict") 
        ),
        ItExpr.IsAny<CancellationToken>()
    );
© www.soinside.com 2019 - 2024. All rights reserved.