How to Unit Test Attributes are Applied to MVC Web API Controller Methods

Photo by Christina Rumpf on Unsplash

Introduction

Before Starting

The Code

Create the Attribute

using Microsoft.AspNetCore.Mvc.Filters;namespace Shop.Attributes
{
public class AccessDeniedExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
// Implementation
// ..
}
}
}

Add the Test

[Test]
public void Get_Should_Be_Decorated_With_AccessDeniedExceptionAttribute()
{
// arrange
var controllerType = typeof(ProductController);
var methodName = nameof(ProductController.Get);
var attributeType = typeof(AccessDeniedExceptionAttribute);
var methodInfo = controllerType.GetMethod(methodName);
var methodAttributes = methodInfo.GetCustomAttributes(false);
// act
var isAttributeApplied = methodAttributes.Any(x => x.GetType() == attributeType);
// assert
Assert.IsTrue(isAttributeApplied);
}

Add the Attribute to the Controller Method

// GET: api/product
[HttpGet]
[AccessDeniedExceptionAttribute]
public IEnumerable<Product> Get()
{
return _productService.GetProducts();
}

Improvements to the code

[Test]
public void Get_Should_Be_Decorated_With_AccessDeniedExceptionAttribute()
{
[...]
var methodInfo = controllerType.GetMethod(methodName);
var methodAttributes = methodInfo.GetCustomAttributes(false);
var isAttributeApplied = methodAttributes
.Any(x => x.GetType() == attributeType);
[...]
}
public static bool IsDecoratedWithAttribute(Type controllerType, Type attributeType, string methodName)
{
var methodInfo = controller.GetMethod(methodName);
var methodAttributes = methodInfo.GetCustomAttributes(false);

return methodAttributes
.Any(x => x.GetType() == attributeType);
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store