1

我从https://stackoverflow.com/a/47807117/1093406添加了一个自定义 InputFormatter,但想为该类添加单元测试。

是否有捷径可寻?我正在查看InputFormatterContextto 的参数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);
    }
}
4

2 回答 2

1

我只创建了一个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,如果有可以使用的东西。

于 2021-09-20T13:14:55.623 回答
1

我找到了 aspnetcore 测试InputFormatter并从这里得到了这个代码:

context = new InputFormatterContext(
                new DefaultHttpContext(),
                "something",
                new ModelStateDictionary(),
                new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
                (stream, encoding) => new StreamReader(stream, encoding));

我还从JsonInputFormatterTestBase得到了一些其他有用的提示

于 2021-09-22T09:08:20.767 回答