我如何测试ActionFilter?

时间:2014-11-27 04:41:51

标签: .net asp.net-mvc asp.net-mvc-4 unit-testing testing

我有一个名为TimeoutFilter的动作过滤器,我将其应用于我的`BaseController':

[TimeoutFilter]
public abstract class BaseController: Controller
{
}

,其中

public class TimeoutFilter : ActionFilterAttribute
{
    private static readonly int TimeoutSeconds;
    static TimeoutFilter()
    {
        int s;
        if (!int.TryParse(ConfigurationManager.AppSettings["MvcActionTimeoutSeconds"], out TimeoutSeconds))
        {
            throw new WebConfigException("appSettings", "MvcActionTimeoutSeconds must be an integer.");
        }
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext.Current.Server.ScriptTimeout = TimeoutSeconds;
        base.OnActionExecuting(filterContext);
    }
}

测试配置部分很简单,但如何测试超时部分?我的直觉告诉我声明TestController: BaseController,然后在该控制器的动作方法中,以某种方式检查HttpContext.Current.Server.ScriptTimeout值是否等于配置值。

1 个答案:

答案 0 :(得分:0)

我认为您无需测试服务器是否实际超时。但您可以测试HttpContext.Current.Server.ScriptTimeout是否设置为与配置中相同的值。

[TestMethod]
public void OnActionExecuting_SetTimeout_TimeoutIsTheSameAsConfig()
{
    var request = new HttpRequestMessage();

    var actionContext = InitializeActionContext(request);

    var filter = new TimeoutFilter();
    filter.OnActionExecuting(actionContext);

    Assert.AReEqual(HttpContext.Current.Server.ScriptTimeout, ConfigurationManager.AppSettings["MvcActionTimeoutSeconds"]);
}

// Code excerpt from http://chimera.labs.oreilly.com/books/1234000001708/ch17.html#_unit_testing_an_actionfilterattribute
private HttpActionContext InitializeActionContext(HttpRequestMessage request)
{
    var configuration = new HttpConfiguration();

    var routeData = new HttpRouteData(route,
        new HttpRouteValueDictionary
        {
            { "controller", "Issues" }
        }
    );

    request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
    var controllerContext = new HttpControllerContext(configuration, routeData, request);
    var actionContext = new HttpActionContext
    {
        ControllerContext = controllerContext
    };

    return actionContext;
}