Recently at work we had to restrict access to a ASP.NET Web API Controller to users in two specific Active Directory groups. We also wanted to create a test that verified this change and I thought it would be nice to share the approach we took to add some coverage.
The Employee Controller
[Authorize(Roles = @"MYDOMAIN\HR,MYDOMAIN\Admin")] public class EmployeeController : ApiController { .... }
The Test
The test we came up with used reflection and ensured that the expected roles were set-up to be authorized.
[TestFixture] public class EmployeeControllerShould { [TestCase(@"MYDOMAIN\HR")] [TestCase(@"MYDOMAIN\Admin")] public void Authorize_for_users_in_role(string role) { var controllerType = typeof(EmployeeController); var attribute = (AuthorizeAttribute)controllerType.GetCustomAttribute(typeof(AuthorizeAttribute), false); Assert.That(attribute.Roles, Is.StringContaining(role)); } }