【问题标题】:Mock IHttpConnectionFeature in ASP.NET Core在 ASP.NET Core 中模拟 IHttpConnectionFeature
【发布时间】:2017-05-19 09:03:59
【问题描述】:

您好,我想在 ASP.NET Core 中模拟 IHttpConnectionFeature

在我的控制器中,我有:

var connectionId = HttpContext.Features.Get<IHttpConnectionFeature>().ConnectionId;

但是如何在我的单元测试中模拟它:

        var controller = new MyController(logger.Object,
            mockService.Object)
        {
            ControllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext()
            }
        };

我收到一条错误消息:

Message = "对象引用未设置为对象的实例。"

【问题讨论】:

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


    【解决方案1】:

    你可以像这样添加它:

    controller.HttpContext.Features.Set<IHttpConnectionFeature>(new HttpConnectionFeature()
    {
         ConnectionId = "test"
    });
    

    【讨论】:

    • 你也可以模拟 IHttpConnectionFeature 而不是一个真实的对象
    • 正如@arni所说:它是一个接口,所以不要在单元测试中创建实例。嘲笑它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 2019-02-10
    • 2020-06-19
    • 2018-10-11
    相关资源
    最近更新 更多