I am trying to run unit tests against a controller decorated with the [Authorize] attribute. The solutions I have found on SO indicate that I should use Moq to mock the authorization. The solution code can be found here.
var controller = new UserController();
var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);
controller.ControllerContext = mock.Object;
I have implemented the above solution in my test:
var controller = new HomeController();
var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);
controller.ControllerContext = mock.Object;
var result = controller.GetStarted();
result.ExecuteResult(mock.Object);
Assert.IsTrue(false); //I am running with a breakpoint here
Result generates, but when I try to execute the result with the mocked controllerContext, I get an error. How do I use the mocked ControllerContext
to test the controller?
The skeleton code for the controller is:
[Authorize]
public ActionResult GetStarted()
{
if (User.Identity.IsAuthenticated)
{
var user = CommonUtil.Instance.UserManager.FindByName(User.Identity.Name);
if (user != null)
{
ViewBag.IsAdministrator = user.Roles.Contains("Administrators");
ViewBag.IsActiveUser = user.Roles.Contains("ActiveUsers");
}
}
return View();
}
I have a feeling this is a trivial fix, but I have no idea what I am doing, so it seems impossible.
Aucun commentaire:
Enregistrer un commentaire