【问题标题】:Unit test custom InputFormatter单元测试自定义 InputFormatter
【发布时间】:2021-09-20 10:08:48
【问题描述】:

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

有没有简单的方法来做到这一点? 我正在查看ReadRequestBodyAsyncInputFormatterContext 参数,它似乎很复杂,需要构造它的许多其他对象,而且看起来很难模拟。 有没有人能够做到这一点?

我在 .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);
    }
}

【问题讨论】:

    标签: c# unit-testing asp.net-core inputformatter


    【解决方案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,如果有可以使用的东西。

    【讨论】:

    • 虽然这个答案没有直接解决我的问题,但您指向 aspnetcore 测试的链接确实为我提供了更多信息,让我能够解决它。
    • 然后将您自己的答案标记为已接受。 ?
    • StackOverflow 不会让您在发布后一小时内将自己的答案标记为已接受 - 我不知道为什么?
    【解决方案2】:

    我找到了 InputFormatter 的 aspnetcore 测试,并从 here 获得了这段代码:

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-05
      • 2018-02-25
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      相关资源
      最近更新 更多