lundi 12 septembre 2016

Unit Testing for Redirection Using Global Authorize Attribute

I'm looking to write a unit test that ensures a user (who is not logged in) cannot access a given page. Although it works perfectly when I test manually, I can't seem to write an automated test that captures what's going on.

In my controller, I have an action I don't want to be accessible to users who aren't logged in.

// GET: Verifier/
[HttpGet]
public ActionResult Index()
{
   return View();
}

In /App_Start/FilterConfig.cs, I've added the AuthorizeAttribute() to redirect users to my login page if they're not authenticated.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AuthorizeAttribute());
    }

This works perfectly, but I can't unit test it effectively!

[TestMethod]
public void VerifierIndex_NotLoggedIn_RedirectsUserToLogin()
{
    // Arrange
    var controller = new VerifierController();

    // Act
    RedirectToRouteResult result = (RedirectToRouteResult) controller.Index();

    // Assert - Fails because result is null
    Assert.AreEqual("Login", result.RouteValues["action"]);
}

The action does return a non-null ActionResult, but I can't seem to get any route values out of that object. Apparently it's failing to cast to RedirectToRouteResult since the action resulting from the authorize attribute is not really a redirect?

How can I effectively test that the "redirect" to the login page was successful?

Thanks!

Aucun commentaire:

Enregistrer un commentaire