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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With