How do I unit test a controller method that has the [Authorize] attribute applied?

You need to mock a context for your controller. Try using Moq

Your arrange would then look like:

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;

You should be able to then do your Act & Assert.

If you haven’t already, I would highly recommend looking through NerdDinner as an example MVC site.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)