Arun Prakash Nagendran
Arun Prakash Nagendran

Reputation: 641

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. 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. I could actually use the RestClient without mocking it. But I wont be able to tell how many times the "Execute" method of this class was called. I need this to test if the retry mechanism kicked in and tried to make the http call "x" number of times

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.'

Upvotes: 0

Views: 800

Answers (1)

bnet
bnet

Reputation: 325

RestSharp already deprecated IRestClient interface at v107. If you want to get API execute count, you can follow the guideline. For example, mix RestSharp and MockHttp to verify execute count:

[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));
}

Upvotes: 1

Related Questions