我从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);
}
}
我找到了 aspnetcore 测试InputFormatter
并从这里得到了这个代码:
context = new InputFormatterContext(
new DefaultHttpContext(),
"something",
new ModelStateDictionary(),
new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
(stream, encoding) => new StreamReader(stream, encoding));
我还从JsonInputFormatterTestBase得到了一些其他有用的提示
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句