How to unit test ActionFilterAttribute

半世苍凉 提交于 2020-04-05 17:48:32

问题


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);
            }
        }
    }

回答1:


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>();
    }
} 


来源:https://stackoverflow.com/questions/46162940/how-to-unit-test-actionfilterattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!