Using the TDD approach in an MVC application, I was wondering how can you ensure that only certain roles have access to the controller. Why should we test for this? Because this is a clearly defined business rule and all business rules need to have Unit Tests where possible.
This is the code, which is quite simple
[Authorize(Roles = "Administrators")] public class AdminController : Controller
What we need to ensure is that a developer does not come along and add more roles or take away the Administrators roles.
We can do this using a Test and going through the Controller using reflection, like this:
[TestMethod]
public void AdminControllerShouldOnlyAvailableToAdministrators()
{
// Arrange
var attributes = typeof(AdminController).GetCustomAttributes(true).ToList();
var countNonAdministrator = 0;
var countAdministrator = 0;
// Act
foreach (var attribute in
attributes.Where(attribute => attribute.GetType() == typeof(AuthorizeAttribute)).Cast<AuthorizeAttribute>())
{
countNonAdministrator = attribute.Roles.Split(',').ToList().Count(role => role.ToString() != "Administrator");
}
foreach (var attribute in
attributes.Where(attribute => attribute.GetType() == typeof(AuthorizeAttribute)).Cast<AuthorizeAttribute>())
{
countAdministrator = attribute.Roles.Split(',').ToList().Count(role => role.ToString() == "Administrator");
}
// Assert
Assert.IsTrue(countNonAdministrator == 0, "Administrators are only allowed to be authorised to use this controller");
Assert.IsTrue(countAdministrator == 1, "You must only have Administrators to be authorised to use this controller");
}