MSTest:注销的单元测试 HttpContext.SignoutAsync

MSTest: Unit Testing HttpContext.SignoutAsync for the logout

在对注销功能进行单元测试时简单地将 Mock HttpContext 传递给控制器​​上下文将抛出以下错误 HttpContext.Signout + 值不能为空(参数'provider')

var mockHttpContext = new Mock<HttpContext>();

       

//设置控制器HttpContext

_controller.ControllerContext.HttpContext = mockHttpContext.Object;

// 现在调用注销操作方法和测试结果

如果您深入了解 SigOutAsync 代码的定义,它期望 Authentication Service Provider 不应为 null 。 因此,除了模拟 HttpContext 之外,您还需要模拟将解决问题的服务提供商。

       //mock the Http Context along with Service provider
        var mockHttpContext = new Mock<HttpContext>();
        var authServiceMock = new Mock<IAuthenticationService>();
        authServiceMock.Setup(_ => _.SignOutAsync(It.IsAny<HttpContext>(), It.IsAny<string>(),It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult((object)null));
        var serviceProviderMock = new Mock<IServiceProvider>();
        serviceProviderMock.Setup(_ => _.GetService(typeof(IAuthenticationService)))
            .Returns(authServiceMock.Object);
        mockHttpContext.Setup(x => x.RequestServices)
          .Returns(serviceProviderMock.Object);

        //set the controller HttpContext
        _controller.ControllerContext.HttpContext = mockHttpContext.Object;
       // Now call the Logout and Test

测试登录功能时可以应用类似的逻辑

也参考这里-