richardszalay/mockhttp

GetMatchCount unexpectedly returning 0.

mrpmorris opened this issue · 3 comments

I've moved to a new client who is using your library.

I'm trying to add a unit test to ensure that if a call to my Customers service fails then no call is made to the Payments service.

I wrote an AnyMockedRequest class that should match any request, but it is not being considered when calling GetMatchCount().

Can you shed any light on this, please?

Thank you!

using System.Net;

var customersApi = new MockHttpMessageHandler();
customersApi
	.When(HttpMethod.Get, "https://customers.com")
	.Respond(HttpStatusCode.OK);

_ = await customersApi.ToHttpClient().GetAsync("https://customers.com");

int matchCount = customersApi.GetMatchCount(AnyMockedRequest.AtAll);
if (matchCount != 1)
	throw new Exception($"Expected 1 match but found {matchCount}.");

public class AnyMockedRequest : IMockedRequest
{
	public static readonly AnyMockedRequest AtAll = new();

	private AnyMockedRequest() { }

	public bool Matches(HttpRequestMessage request) => true;
	public Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken cancellationToken) =>
		throw new InvalidOperationException();
}

Hi @mrpmorris,

Match counts are recorded against the actual IMockedRequest instance returned by When/Respond, GetMatchCount simply returns that count (as opposed to re-evaluating previous requests against the supplied IMockedRequest, which is how I think you've interpreted it).

So if you assign the return value of When/Respond to a variable you can pass that into GetMatchCount and assert that it's 0.

In the meantime I'll review the "Verifying matches" section of the readme to see if I can make it clearer.

Thanks for your fast response!

I'll give it a try tomorrow.

That was just what I needed, thank you for your help and thank you for being so prompt!