#nullable enable using System.Net; namespace Bit.Test.Common.MockedHttpClient; public class MockedHttpMessageHandler : HttpMessageHandler { private readonly List _matchers = new(); /// /// The fallback handler to use when the request does not match any of the provided matchers. /// /// A Matcher that responds with 404 Not Found public MockedHttpResponse Fallback { get; set; } = new(HttpStatusCode.NotFound); protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var matcher = _matchers.FirstOrDefault(x => x.Matches(request)); if (matcher == null) { return await Fallback.RespondToAsync(request); } return await matcher.RespondToAsync(request); } /// /// Instantiates a new HttpRequestMessage matcher that will handle requests in fitting with the returned matcher. Configuration can be chained. /// /// /// /// public T When(T requestMatcher) where T : IHttpRequestMatcher { _matchers.Add(requestMatcher); return requestMatcher; } /// /// Instantiates a new HttpRequestMessage matcher that will handle requests in fitting with the returned matcher. Configuration can be chained. /// /// /// /// public HttpRequestMatcher When(string uri) { var matcher = new HttpRequestMatcher(uri); _matchers.Add(matcher); return matcher; } /// /// Instantiates a new HttpRequestMessage matcher that will handle requests in fitting with the returned matcher. Configuration can be chained. /// /// /// /// public HttpRequestMatcher When(Uri uri) { var matcher = new HttpRequestMatcher(uri); _matchers.Add(matcher); return matcher; } /// /// Instantiates a new HttpRequestMessage matcher that will handle requests in fitting with the returned matcher. Configuration can be chained. /// /// /// /// public HttpRequestMatcher When(HttpMethod method) { var matcher = new HttpRequestMatcher(method); _matchers.Add(matcher); return matcher; } /// /// Instantiates a new HttpRequestMessage matcher that will handle requests in fitting with the returned matcher. Configuration can be chained. /// /// /// /// public HttpRequestMatcher When(HttpMethod method, string uri) { var matcher = new HttpRequestMatcher(method, uri); _matchers.Add(matcher); return matcher; } /// /// Instantiates a new HttpRequestMessage matcher that will handle requests in fitting with the returned matcher. Configuration can be chained. /// /// /// /// public HttpRequestMatcher When(Func matcher) { var requestMatcher = new HttpRequestMatcher(matcher); _matchers.Add(requestMatcher); return requestMatcher; } /// /// Converts the MockedHttpMessageHandler to a HttpClient that can be used in your tests after setup. /// /// public HttpClient ToHttpClient() { return new HttpClient(this); } }