【问题标题】:How to count the number of times a method is called for a mocked concrete class?如何计算模拟具体类调用方法的次数?
【发布时间】:2022-08-02 10:50:34
【问题描述】:

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

我在嘲笑 RestSharp 的 \"RestClient\" 类。我实际上可以使用 RestClient 而无需嘲笑它。但我无法说出这个类的“执行”方法被调用了多少次。我需要这个来测试重试机制是否启动并尝试进行 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.\'

  • 你能分享你在嘲笑什么方法,以及你是如何做到的吗?
  • \"我得到一个异常\"什么异常?通常,尝试模拟不是接口的东西是个坏主意。
  • Exception-\"Non-overridable members (here: RestClient.Execute) may not be used in setup / verification expressions.\'我可以避免嘲笑RestClient并直接使用它,但我无法计算内部方法的次数它被称为
  • 如果无法设置方法,则无法使用 Moq 来计算调用了多少次。

标签: c# moq


【解决方案1】:

RestSharp 已在 v107 中弃用 IRestClient 接口。如果要获取 API 执行次数,可以关注guideline。例如,混合使用 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));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    相关资源
    最近更新 更多