57 lines
2.2 KiB
C#
57 lines
2.2 KiB
C#
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace DocumentService.Tests.Unit.Client;
|
|
|
|
/// <summary>
|
|
/// Reusable fake <see cref="HttpMessageHandler"/> for unit-testing HTTP clients.
|
|
/// Captures the outgoing request and returns the configured response.
|
|
/// </summary>
|
|
internal sealed class MockHttpMessageHandler : HttpMessageHandler
|
|
{
|
|
private readonly HttpResponseMessage _response;
|
|
|
|
/// <summary>The last request that was sent through this handler.</summary>
|
|
public HttpRequestMessage? LastRequest { get; private set; }
|
|
|
|
public MockHttpMessageHandler(HttpResponseMessage response)
|
|
{
|
|
_response = response;
|
|
}
|
|
|
|
// ?? convenience factories ????????????????????????????????????????????????
|
|
|
|
/// <summary>Creates a handler that returns 200 OK with a JSON-serialised body.</summary>
|
|
public static MockHttpMessageHandler ReturningJson<T>(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);
|
|
}
|
|
|
|
/// <summary>Creates a handler that returns 200 OK with raw bytes as the body.</summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>Creates a handler that returns the given status code with no body.</summary>
|
|
public static MockHttpMessageHandler ReturningStatus(HttpStatusCode status)
|
|
=> new(new HttpResponseMessage(status));
|
|
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
{
|
|
LastRequest = request;
|
|
return Task.FromResult(_response);
|
|
}
|
|
}
|