如何对 TextOutputFormatter 进行单元测试

问题描述 投票:0回答:2

我已经编写了一个按预期工作的

TextOutputFormatter
,但现在我想围绕它进行一些单元测试。
WriteResponseBodyAsync
的第一个参数是
OutputFromatterWriteContext
,我不确定如何实例化。

我尝试使用以下内容,但

context.HttpContext.Response.Body
最终成为空流。

[Fact]
public async Task ShouldPrefixAsync()
{
    // Arrange
    var output = Guid.NewGuid().ToString();

    var context = new OutputFormatterWriteContext(
        new DefaultHttpContext(),
        (stream, encoding) => new HttpResponseStreamWriter(stream, encoding),
        typeof(string),
        output
    ) {
        ContentType = "application/json"
    };

    // Act
    var filter = new XssJsonOutputFormatter();
    await filter.WriteResponseBodyAsync(context, Encoding.UTF8);

    using var reader = new StreamReader(context.HttpContext.Response.Body);
    var json = await reader.ReadToEndAsync();

    var wanted = $"{XssJsonOutputFormatter.XssPrefix}{output}";

    // Assert
    Assert.Equal(wanted, json);
}
c# unit-testing asp.net-core asp.net-core-6.0
2个回答
2
投票

无法读取响应正文 我认为你可以尝试用可以在单元测试中读取的内存流替换默认主体

var httpcontext = new DefaultHttpContext();
httpcontext.Response.Body = new MemoryStream();

0
投票

也许为时已晚,但正如冯睿凯所说,更换仍然是最佳选择。

https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/test/Formatters/SystemTextJsonOutputFormatterTest.cs

© www.soinside.com 2019 - 2024. All rights reserved.