Files
2026-09-02 09:38:45 +08:00

59 lines
2.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace Yh.SchClass.OpenApi.Tests;
/// <summary>
/// 伪造 <see cref="HttpMessageHandler"/>:捕获最近一次请求并回放预设响应。
/// 与 <c>Yh.Platform.OpenApi.Tests</c> 的 FakeHandler 同构,便于两个 SDK 的测试互相参照。
/// </summary>
public sealed class FakeHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, string?, HttpResponseMessage> _responder;
public FakeHandler(Func<HttpRequestMessage, string?, HttpResponseMessage> responder)
{
_responder = responder;
}
/// <summary>最近一次捕获到的请求。</summary>
public HttpRequestMessage? LastRequest { get; private set; }
/// <summary>最近一次请求体(无请求体时为 null)。</summary>
public string? LastRequestBody { get; private set; }
/// <summary>最近一次请求体的 Content-Type(无请求体时为 null)。</summary>
public string? LastContentType { get; private set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
LastRequest = request;
if (request.Content == null)
{
LastRequestBody = null;
LastContentType = null;
}
else
{
LastRequestBody = await request.Content.ReadAsStringAsync(cancellationToken);
LastContentType = request.Content.Headers.ContentType?.MediaType;
}
return _responder(request, LastRequestBody);
}
/// <summary>回放一段固定 JSON(application/json)。</summary>
public static FakeHandler Json(HttpStatusCode statusCode, string json)
=> new((_, _) => new HttpResponseMessage(statusCode)
{
Content = new StringContent(json, Encoding.UTF8, "application/json"),
});
/// <summary>回放指定状态码且无响应体(模拟 204 / 404 空响应)。</summary>
public static FakeHandler Empty(HttpStatusCode statusCode)
=> new((_, _) => new HttpResponseMessage(statusCode));
/// <summary>回放纯文本响应(模拟非 JSON 的错误页)。</summary>
public static FakeHandler Text(HttpStatusCode statusCode, string text)
=> new((_, _) => new HttpResponseMessage(statusCode)
{
Content = new StringContent(text, Encoding.UTF8, "text/plain"),
});
}