35

I've searched stackoverflow and googled four a couple of hours and still not found any solution for my "trivial" problem.

If you write unit test for your filtered [Authorize] ActionResult, how do you solve the problem to fake that user is authenticated?

I have a lot of ActionResult methods that are filtered with [Authorize] and I want to test all of my ActionResult methods regardless if they are filtered with [Authorize] or not.

A simple example of what i mean:

[TestMethod]
public void Create_Get_ReturnsView()
{
 // Arrange
 var controller = new UserController();
 // Act
 var result = controller.Create();
 // Assert
 Assert.IsNotNull(result as ViewResult);
}

[Authorize]
public ActionResult Create()
{
 return View("Create");
}

As of now the tests don't even hit the ActionResult method because of the [Authorize] filter, exception thrown is: System.NullReferenceException: Object reference not set to an instance of an object.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Webking
  • 1,822
  • 2
  • 20
  • 28
  • 1
    There's something you're not showing us. The test you show won't execute *any* action filters. Maybe you have code which will, but it's not in your question. How about the whole call stack for the error, for starters? – Craig Stuntz Dec 09 '09 at 22:11

1 Answers1

33

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.

CodeWarrior
  • 508
  • 3
  • 13
Nate
  • 1,669
  • 15
  • 22
  • I might argue that you don't need to really test this at all. The attribute is already well tested by the team that wrote ASP.NET MVC. You can download the source and see for yourself. – Jeff Putz Jun 25 '10 at 03:49
  • 9
    It isn't to test the `[Authorized]` attribute, it's to get around it to test the `ActionResult` methods – AndyMcKenna Nov 11 '11 at 21:34
  • 3
    @Jeff Putz wouldn't you also want to test that someone hadn't removed the attribute during a refactor? – Adam Naylor Apr 29 '13 at 14:02
  • 1
    I am not sure what this test does? It seems do nothing. – Liang Wu Jun 07 '13 at 22:38