我已经编写了一个按预期工作的
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);
}