unit-testing.net-corexunitxunit.netactionfilterattribute

How to unit test ActionFilterAttribute


I'm looking to test an ActionFilterAttribute in a .NET Core 2.0 API project and wondering the best way to go about it. Note, I'm not trying to test this through a controller action, merely test the ActionFilterAttribute itself.

How might I go about testing this:

    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                context.Result = new BadRequestObjectResult(context.ModelState);
            }
        }
    }

Solution

  • Create an instance of the context pass it to the filter and assert the expected behavior

    For example

    [TestClass]
    public class ValidateModelAttributeTest {
        [TestMethod]
        public void Invalid_ModelState_Should_Return_BadRequestObjectResult() {
            //Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("", "error");
            var httpContext = new DefaultHttpContext();
            var context = new ActionExecutingContext(
                new ActionContext(
                    httpContext: httpContext,
                    routeData: new RouteData(),
                    actionDescriptor: new ActionDescriptor(),
                    modelState: modelState
                ),
                new List<IFilterMetadata>(),
                new Dictionary<string, object>(),
                new Mock<Controller>().Object);
    
            var sut = new ValidateModelAttribute();
    
            //Act
            sut.OnActionExecuting(context);
    
            //Assert
            context.Result.Should().NotBeNull()
                .And.BeOfType<BadRequestObjectResult>();
        }
    }