我从https://stackoverflow.com/a/47807117/1093406添加了一个自定义 InputFormatter,但想为该类添加单元测试。
是否有捷径可寻?我正在查看InputFormatterContext
to 的参数ReadRequestBodyAsync
,它似乎很复杂,需要构造它的许多其他对象,而且看起来很难模拟。有没有人能够做到这一点?
我在 .Net5 上使用 xUnit 和 Moq
代码
public class RawJsonBodyInputFormatter : InputFormatter
{
public RawJsonBodyInputFormatter()
{
this.SupportedMediaTypes.Add("application/json");
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync();
return await InputFormatterResult.SuccessAsync(content);
}
}
protected override bool CanReadType(Type type)
{
return type == typeof(string);
}
}