Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to unit test a page in my ASP.NET MVC application that, when posted to, will delete a user's item. I want to restrict this page so that it can only be posted to by the owner of said item. Originally, I wanted to just stick a quick check in the controller that checked if the HttpContext.Current.User.Identity.Name is equal to the owner of the item, but I quickly realized that unit testing this would be difficult.

Should I create an interface that provides a way to access the current logged-in user's name?

like image 509
Kevin Pang Avatar asked Nov 17 '08 18:11

Kevin Pang


People also ask

How can I get username in MVC?

to get the current user name, however if you want to see all users record then you need to get the username by using its id, you can do this operation by joining Users table on user.id key or you can use it in View by having a method that take user id as parameter and return its Name.

How to check user Authentication in mvc?

Choose ASP.NET Web Application template and select MVC option. In this application, we will check the user authentication before every request execution. Hence, we need a database and a “User” table inside the database. We will validate the user information before every request.

How to get login user in ASP Net?

In ASP.NET, please use User.Identity.Name to get the logon user. User.Identity.Name might be empty if Anonymous Authentication is enabled in IIS. Here is the logical to check if the identity is available. ' Gets the name if authenticated.


1 Answers

You can use this code

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;
}

It uses moq lib

like image 193
Sly Avatar answered Oct 07 '22 23:10

Sly