我有一个名为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
值是否等于配置值。
答案 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;
}