richardszalay/mockhttp

Retrying the exact same request

Closed this issue · 2 comments

Is there a way to mock a situation where the exact same request is made twice but the response is different? The scenario is that my class has automatic retry in certain cases and I want to unit test the 'retry' code. I wrote the following unit test but the second mock is never used, only the first one which causes the Assert.IsTrue to fail.

// Arrange
var mockHttp = new MockHttpMessageHandler();

// First attempt, we return HTTP 429 which means TOO MANY REQUESTS
mockHttp.When(HttpMethod.Get, "https://my.api.com/myendpoint")
	.With(request => request.Content == null)
	.Respond((HttpStatusCode)429);

// Second attempt, we return the expected result
mockHttp.When(HttpMethod.Get, "https://my.api.com/myendpoint")
	.With(request => request.Content == null)
	.Respond("application/json", "{'name' : 'This is a test'}");

var httpClient = new HttpClient(mockHttp);
var client = new MyClient(httpClient);

// Act
var result = client.GetAsync("myendpoint", CancellationToken.None).Result;

// Assert
mockHttp.VerifyNoOutstandingExpectation();
mockHttp.VerifyNoOutstandingRequest();
Assert.IsTrue(result.IsSuccessStatusCode);

By the way, I was a little bit surprised to notice that VerifyNoOutstandingExpectation does not fail despite the fact that only one of my two mocks is invoked.

Sure, you have two choices here:

If there are no unrelated requests that might occur at an undefined order, you can use Expect rather than When.

Otherwise, you could use When with a Respond overload that takes a function. Then you could return a different value each time, perhaps popping them off a queue.

VerifyNoOutstandingExpectation only works with Expect mocks. Take a look at "Expect vs When" in the readme.

Request Expectations match only once and in the order they were added in.

This is exactly what I need. Thanks for the tip.