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

时间:2013-09-25 13:42:22

标签: c# asp.net-mvc unit-testing

我在控制器中有代码消耗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

我正在使用Moq进行模拟

2 个答案:

答案 0 :(得分:44)

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

        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; 

答案 1 :(得分:2)

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

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;