How do you stub User.Identity.Name in ASP.NET MVC?

I am trying to execute a unit test page in my ASP.NET MVC application, which when submitted will remove the user element. I want to limit this page so that it can only be submitted by the owner of the specified item. Initially, I just wanted to stick to a quick check in the controller, which checked if the name HttpContext.Current.User.Identity.Name owned the element, but I quickly realized that unit testing would be difficult.

Should I create an interface that provides a way to access the current username registered on the network?

+5
source share
3 answers

, , , , , HttpContext.Current.User IPrincipal HttpContext.Current.User.Identity IIdentity.

, , IIdentity HttpContext.Current.User.Identity

, !

+4

Controller CreateControllerAs(string userName) {

  var mock = new Mock<ControllerContext>();
  mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
  mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);

  var controller = new SomeController();
  controller.ControllerContext = mock.Object;

  return controller;
}

moq lib

+5

I am using Thread.CurrentPrincipal.Identity.Name. It is trivial to create a GenericPrincipal for the unit test and attach it.

+2
source

All Articles