How do I unit test a custom ActionFilter in ASP.Net MVC

狂风中的少年 提交于 2019-11-29 01:11:27
Ryan

You just need to test the filter itself. Just create an instance and call the OnActionExecuted() method with test data then check the result. It helps to pull the code apart as much as possible. Most of the heavy lifting is done inside the CsvResult class which can be tested individually. You don't need to test the filter on an actual controller. Making that work is the MVC framework's responsibility.

public void AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson()
{
    var context = new ActionExecutedContext();
    context.HttpContext = // mock an http context and set the accept-type. I don't know how to do this, but there are many questions about it.
    context.Result = new ViewResult(...); // What your controller would return
    var filter = new AcceptTypesAttribute(HttpContentTypes.Json);

    filter.OnActionExecuted(context);

    Assert.True(context.Result is JsonResult);
}

I just stumbled upon this blog post which seems the right way to me, he uses Moq

Edit

Okay so what this chap is doing is mocking the HTTPContext, but also we need to setup a ContentType in the request:

    // Mock out the context to run the action filter.
    var request = new Mock<HttpRequestBase>();
    request.SetupGet(r => r.ContentType).Returns("application/json");

    var httpContext = new Mock<HttpContextBase>();
    httpContext.SetupGet(c => c.Request).Returns(request.Object);

    var routeData = new RouteData(); //
    routeData.Values.Add("employeeId", "123");

    var actionExecutedContext = new Mock<ActionExecutedContext>();
    actionExecutedContext.SetupGet(r => r.RouteData).Returns(routeData);
    actionExecutedContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object);

    var filter = new EmployeeGroupRestrictedActionFilterAttribute();

    filter.OnActionExecuted(actionExecutedContext.Object);

Note - I have not tested this myself

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