我已经从https://stackoverflow.com/a/47807117/1093406添加了一个自定义InputFormatter,但希望为该类添加单元测试。
有什么简单的方法可以做到这一点吗?我正在查看ReadRequestBodyAsync的InputFormatterContext参数,它看起来很复杂,需要许多其他对象来构造它,而且看起来很难模拟。有没有人能做到这一点?
我在.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);
}
}发布于 2021-09-22 09:08:21
我找到了InputFormatter的aspnetcore测试,并从here获得了以下代码
context = new InputFormatterContext(
new DefaultHttpContext(),
"something",
new ModelStateDictionary(),
new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
(stream, encoding) => new StreamReader(stream, encoding));我还从JsonInputFormatterTestBase获得了其他一些有用的提示
发布于 2021-09-20 13:14:56
我只创建了一个用于模拟的ControllerContext,它还必须实例化一个HttpContext
controllerBase.ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext
{
RequestServices = new ServiceCollection()
.AddOptions()
.AddAuthenticationCore(options =>
{
options.DefaultScheme = MyAuthHandler.SchemeName;
options.AddScheme(MyAuthHandler.SchemeName, s => s.HandlerType = typeof(MyAuthHandler));
}).BuildServiceProvider()
}
};要模拟您的案例中的其他属性,您可以看看BodyModelBinderTests.cs,如果有什么可以使用的话。
https://stackoverflow.com/questions/69252633
复制相似问题