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.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.