I wanted to Unit Test (in BDD I’d call it a specification) that the controller had the authorize attribute so I found this approach in a GoodSearch a while back and forgotten who to give credit for it, but I thought I’d post it, so I won’t have to search for it next time. I put this in a base class and it’s been very useful.
EDIT: March 21st, 2013 I added a way to also verify the correct roles are in the attribute. This is especially nice, sine the attribute takes strings.
[Authorize(Roles = "Super Admin, User Admin")] public void MyController2{}
[Authorize] public void MyController{}
///
///
if (authorizeAttribute == null)
{
return;
}
bool all = authorizeAttribute.Roles.Split(',').All(r => roles.Contains(r.Trim()));
Assert.IsTrue(all);
}
And to call it:
[TestMethod] [TestCategory("MyController")] public void It_Should_Require_Authorization() { // where this.Controller is the controller you are testing
this.It_Should_Require_Authorization(this.Controller); }
[TestMethod] [TestCategory("MyController2")] public void It_Should_Require_Authorization() { var roles = new[] { “Super Admin”, “User Admin” }; this.It_Should_Require_Authorization(this.Controller, roles); }
