[英]How to count the number of times a method is called for a mocked concrete class?
I have a mocked concrete class and when I try to count the number of times a method "x" is invoked in the class, I get an exception.我有一个模拟的混凝土 class,当我尝试计算在 class 中调用方法“x”的次数时,我得到了一个异常。 I understand this is not a mocked interface and the method is not overridable.我知道这不是一个模拟接口,并且该方法不可覆盖。 Is there any other way I can count?有没有其他方法可以计算?
I am mocking "RestClient" class of RestSharp.我是 RestSharp 的 mocking "RestClient" class。 I could actually use the RestClient without mocking it.我实际上可以在没有 mocking 的情况下使用 RestClient。 But I wont be able to tell how many times the "Execute" method of this class was called.但我无法说出这个 class 的“执行”方法被调用了多少次。 I need this to test if the retry mechanism kicked in and tried to make the http call "x" number of times我需要这个来测试重试机制是否启动并试图使 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 already deprecated IRestClient
interface at v107. RestSharp 在 v107 中已经弃用IRestClient
接口。 If you want to get API execute count, you can follow the guideline .如果要获取 API 执行计数,可以按照指南。 For example, mix RestSharp and MockHttp to verify execute count:例如,混合使用 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.