Unit Test to assure the Authorized Attribute in MVC is applied

December 11, 2017    Development UnitTesting Asp.Net MVC AutomatedTesting .Net

Unit Test to assure the Authorized Attribute in MVC is applied

Originally posted on GeeksWithBlogs.net .

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 awhile 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.

EDIT: December 11, 2017. This still works today in Asp.Net MVC. I haven’t tried it in Core, but assume it works there as well.

The helper code

[Authorize(Roles = "Super Admin, User Admin")]
public void MyController2{}

[Authorize]
public void MyController{}
/// <summary> It should require authorization for Controller or ApiController.</summary>
/// <param name="controller"> The controller.</param>
/// <returns>The Authorize Attribute from the controller .</returns>
protected AuthorizeAttribute It_Should_Require_Authorization(object controller)
{
    var type = controller.GetType();
    var attributes = type.GetCustomAttributes(typeof(AuthorizeAttribute), true);
    Assert.IsTrue(attributes.Any(), "No AuthorizeAttribute found");
    return attributes.Any() ? attributes[0] as AuthorizeAttribute : null;
}

/// <summary> It should require authorization for Controller or ApiController.</summary>
/// <param name="controller"> The controller.</param>
/// <param name="roles">      The roles.</param>
protected void It_Should_Require_Authorization(object controller, string[] roles)
{
    var authorizeAttribute = this.It_Should_Require_Authorization(controller);
    if (!roles.Any())
    {
        return;
    }

    if (authorizeAttribute == null)
    {
        return;
    }

    bool all = authorizeAttribute.Roles.Split(',').All(r => roles.Contains(r.Trim()));
    Assert.IsTrue(all);
}

The unit tests

[TestMethod]
public void It_Should_Require_Authorization()
{
  // where this.Controller is the controller you are testing  
  this.It_Should_Require_Authorization(this.Controller);
}

[TestMethod]
public void It_Should_Require_Authorization()
{
    var roles = new[] { "Super Admin", "User Admin" };
    this.It_Should_Require_Authorization(this.Controller, roles);
}


Watch the Story for Good News
I gladly accept BTC Lightning Network tips at [email protected]

Please consider using Brave and adding me to your BAT payment ledger. Then you won't have to see ads! (when I get to $100 in Google Ads for a payout, I pledge to turn off ads)

Use Brave

Also check out my Resources Page for referrals that would help me.


Swan logo
Use Swan Bitcoin to onramp with low fees and automatic daily cost averaging and get $10 in BTC when you sign up.