如何在 MVC 4 Asp.Net 中模拟 HttpContext.User.Identity.Name

本文关键字:HttpContext 模拟 User Identity Name Net MVC Asp | 更新日期: 2023-09-27 18:32:41

我在控制器中有消耗HttpContext

的代码
public ActionResult Index()
{
   var currentUser=HttpContext.User.Identity.Name;
   ......
}

尝试像这样使用 NUnit 编写测试

[Test]
public void CanDisplayRequest()
{
    //Act
    var result=  (ViewResult)_requestController.Index();
    //Assert
    Assert.IsInstanceOf<OrderRequest>(resut.Model);
}

测试将失败,因为它找不到HttpContext

那我怎么能嘲笑HttpContext.Current.User.Identity.Name

我正在使用最小起订量进行嘲笑

如何在 MVC 4 Asp.Net 中模拟 HttpContext.User.Identity.Name

您可以使用假主体使用假上下文初始化控制器,如下所示

var fakeHttpContext = new Mock<HttpContextBase>();
var fakeIdentity = new GenericIdentity("User");
var principal = new GenericPrincipal(fakeIdentity, null);
fakeHttpContext.Setup(t => t.User).Returns(principal);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);
_requestController = new RequestController();
//Set your controller ControllerContext with fake context
_requestController.ControllerContext = controllerContext.Object;

要仅使用Microsoft测试(没有第三方框架)来执行此操作,您可以执行以下操作:

public class MockHttpContextBase : HttpContextBase
{
    public override IPrincipal User { get; set; }
}

然后。。。

        var userToTest = "User";
        string[] roles = null;
        var fakeIdentity = new GenericIdentity(userToTest);
        var principal = new GenericPrincipal(fakeIdentity, roles);
        var fakeHttpContext = new MockHttpContextBase { User = principal };
        var controllerContext = new ControllerContext
        {
            HttpContext = fakeHttpContext
        };
        // This is the controller that we wish to test:
        _requestController = new RequestController();
        // Now set the controller ControllerContext with fake context
        _requestController.ControllerContext = controllerContext;