在 ASP.NET Core 中模拟 IHttpConnectionFeature

Cie*_*eja 2 c# asp.net unit-testing httpcontext asp.net-core

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

在我的控制器中,我有:

var connectionId = HttpContext.Features.Get<IHttpConnectionFeature>().ConnectionId;
Run Code Online (Sandbox Code Playgroud)

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

        var controller = new MyController(logger.Object,
            mockService.Object)
        {
            ControllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext()
            }
        };
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息:

消息 = "未将对象引用设置为对象的实例。"

Cie*_*eja 5

你可以像这样添加它:

controller.HttpContext.Features.Set<IHttpConnectionFeature>(new HttpConnectionFeature()
{
     ConnectionId = "test"
});
Run Code Online (Sandbox Code Playgroud)