繁体   English   中英

如何计算为模拟混凝土 class 调用方法的次数?

[英]How to count the number of times a method is called for a mocked concrete class?

我有一个模拟的混凝土 class,当我尝试计算在 class 中调用方法“x”的次数时,我得到了一个异常。 我知道这不是一个模拟接口,并且该方法不可覆盖。 有没有其他方法可以计算?

我是 RestSharp 的 mocking "RestClient" class。 我实际上可以在没有 mocking 的情况下使用 RestClient。 但我无法说出这个 class 的“执行”方法被调用了多少次。 我需要这个来测试重试机制是否启动并试图使 http 调用“x”次数

Mock<RestClient> _mockRestClient = new Mock<RestClient>(mockHttpHandler, true);
//Act
            var res = _httpClient.ExecuteTaskWithPolicy(_mockRestClient.Object, _mockRestRequest.Object, policy);

            //Assert
            _mockRestClient.Verify(x => x.Execute(_mockRestRequest.Object), Times.Exactly(4));
Non-overridable members (here: RestClient.Execute) may not be used in setup / verification expressions.'

RestSharp 在 v107 中已经弃用IRestClient接口。 如果要获取 API 执行计数,可以按照指南 例如,混合使用 RestSharp 和MockHttp来验证执行计数:

[Test]
public async Task TestAsync()
{
    // arrange
    using var mockHttp = new MockHttpMessageHandler();
    var getFooMockedRequest = mockHttp
        .When("http://localhost/api/user/foo")
        .Respond("application/json", "{'name' : 'foo'}");
    var getBarMockedRequest = mockHttp
        .When("http://localhost/api/user/bar")
        .Respond("application/json", "{'name' : 'bar'}");

    using var client = new RestClient(
        new RestClientOptions("http://localhost/api")
        {
            ConfigureMessageHandler = _ => mockHttp
        });

    // act
    await client.GetAsync(new RestRequest("/user/foo"));
    await client.GetAsync(new RestRequest("/user/foo"));
    await client.GetAsync(new RestRequest("/user/foo"));

    await client.GetAsync(new RestRequest("/user/bar"));
    await client.GetAsync(new RestRequest("/user/bar"));

    // assert
    Assert.AreEqual(3, mockHttp.GetMatchCount(getFooMockedRequest));
    Assert.AreEqual(2, mockHttp.GetMatchCount(getBarMockedRequest));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM