using System.Net; using System.Net.Http; using System.Text; using System.Text.Json; namespace DocumentService.Tests.Unit.Client; /// /// Reusable fake for unit-testing HTTP clients. /// Captures the outgoing request and returns the configured response. /// internal sealed class MockHttpMessageHandler : HttpMessageHandler { private readonly HttpResponseMessage _response; /// The last request that was sent through this handler. public HttpRequestMessage? LastRequest { get; private set; } public MockHttpMessageHandler(HttpResponseMessage response) { _response = response; } // ?? convenience factories ???????????????????????????????????????????????? /// Creates a handler that returns 200 OK with a JSON-serialised body. public static MockHttpMessageHandler ReturningJson(T body, HttpStatusCode status = HttpStatusCode.OK) { var json = JsonSerializer.Serialize(body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); var response = new HttpResponseMessage(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; return new MockHttpMessageHandler(response); } /// Creates a handler that returns 200 OK with raw bytes as the body. public static MockHttpMessageHandler ReturningBytes(byte[] bytes, string mediaType = "application/octet-stream", HttpStatusCode status = HttpStatusCode.OK) { var response = new HttpResponseMessage(status) { Content = new ByteArrayContent(bytes) { Headers = { ContentType = new(mediaType) } } }; return new MockHttpMessageHandler(response); } /// Creates a handler that returns the given status code with no body. public static MockHttpMessageHandler ReturningStatus(HttpStatusCode status) => new(new HttpResponseMessage(status)); protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { LastRequest = request; return Task.FromResult(_response); } }