I have a method in a regular mvc controller that checks the user's identity to see which page the user should be directed to. However, building a unit test against this method raises an "object reference not set" error as User is always null when the method is run as part of a test.
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Administrator"))
{
return RedirectToAction("Console");
}
ViewBag.StatusMessage = "You are logged in but do not have sufficient permissions.";
}
else
{
ViewBag.StatusMessage = "Please log in";
}
return View();
}
I have tried various solutions offered at Writing Unit Test for methods that use User.Identity.Name in ASP.NET Web API. These generally use something like the following inside the body of the unit test:
var identity = new GenericIdentity("UserName");
Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
var controller = new FooController();
This approach works fine if the Controller is an ApiController - i.e. a controller for a WebApi project but it does not seem to work for a regular web mvc controller. The User object remains null. How to solve?
FooContrioller(IProvidesUser userProvider)
) – Alexei Levenkov