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
- [TestMethod]
- public void PreviousSiteUserConversion_Authorization_Attributes_Have_Been_Applied()
- {
- // Arrange
- MethodInfo varietalMethod = typeof(AdminController).GetMethod("PreviousSiteUserConversion", new Type[] { });
- // Act
- var attributes = varietalMethod.GetCustomAttributes(typeof(AuthorizeAttribute), true);
- // Assert
- Assert.IsNotNull(attributes);
- Assert.AreEqual(1, attributes.Length);
- var authAttribute = (AuthorizeAttribute)attributes[0];
- string[] roles = authAttribute.Roles.Split(new char[] { ',' });
- Assert.IsTrue(roles.Contains(RoleNames.Admin));
- }
And here is the code:
Working Code
- public class AdminController : Controller
- {
- [Authorize(Roles = RoleNames.Admin)]
- public ActionResult PreviousSiteUserConversion()
- {
- return View();
- }
- }
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 Reply