title: Unit testing ASP.Net MVC Authorize attribute to verify redirect to login page
body: <p>This is probably going to turn out to be a case of just needing another pair of eyes. I must be missing something, but I cannot figure out why this kind of thing cannot be tested for. I'm basically trying to ensure that unauthenticated users cannot access the view by marking the controller with the [Authorize] attribute and I'm trying to tests this using the following code:</p>
  
  <pre><code>[Fact]
  public void ShouldRedirectToLoginForUnauthenticatedUsers()
  {
      var mockControllerContext = new Mock&lt;ControllerContext&gt;()
                           { DefaultValue = DefaultValue.Mock };
      var controller = new MyAdminController() 
                {ControllerContext = mockControllerContext.Object};
      mockControllerContext.Setup(c =&gt;
                 c.HttpContext.Request.IsAuthenticated).Returns(false);
      var result = controller.Index();
      Assert.IsAssignableFrom&lt;RedirectResult&gt;(result);
  }
  </code></pre>
  
  <p>The RedirectResult I'm looking for is some kind of indication that the user is being redirected to the login form, but instead a ViewResult is always returned and when debugging I can see that the Index() method is successfully hit even though the user is not authenticated.</p>
  
  <p>Am I doing something wrong? Testing at the wrong level? Should I rather be testing at the route level for this kind of thing?</p>
  
  <p>I know that the [Authorize] attribute is working, because when I spin up the page, the login screen is indeed forced upon me - but how do I verify this in a test?</p>
  
  <p>The controller and index method are very simple just so that I can verify the behaviour. I've included them for completeness:</p>
  
  <pre><code>[Authorize]
  public class MyAdminController : Controller
  {
      public ActionResult Index()
      {
          return View();
      }
  }
  </code></pre>
  
  <p>Any help appreciated...</p>