• April 2010
    M T W T F S S
     1234
    567891011
    12131415161718
    19202122232425
    2627282930  
  • Latest Posts

  • Latest Comments

  • Archives

Unit Test Authorize Attribute

Technorati Tags: ,,,

Story: I want to write a unit test to ensure that the Authorize attribute is applied to a controller ActionResult or ViewResult so that security is tested.

Here is the test:

Unit Test
  1. [TestMethod]
  2. public void PreviousSiteUserConversion_Authorization_Attributes_Have_Been_Applied()
  3. {
  4.     // Arrange
  5.     MethodInfo varietalMethod = typeof(AdminController).GetMethod("PreviousSiteUserConversion", new Type[] { });
  6.  
  7.     // Act
  8.     var attributes = varietalMethod.GetCustomAttributes(typeof(AuthorizeAttribute), true);
  9.  
  10.     // Assert
  11.     Assert.IsNotNull(attributes);
  12.     Assert.AreEqual(1, attributes.Length);
  13.     var authAttribute = (AuthorizeAttribute)attributes[0];
  14.     string[] roles = authAttribute.Roles.Split(new char[] { ',' });
  15.     Assert.IsTrue(roles.Contains(RoleNames.Admin));
  16. }

And here is the code:

Working Code
  1. public class AdminController : Controller
  2. {
  3.     [Authorize(Roles = RoleNames.Admin)]
  4.     public ActionResult PreviousSiteUserConversion()
  5.     {
  6.         return View();
  7.     }
  8.  
  9. }

The unit test does pass.

There are also some great posts out there about using strongly typed role and user names. My needs are pretty simple… I just need a single role that I strongly type.

Leave a Comment