2011-12-14 74 views
14

因此,我创建了一个基于此项目http://www.codeproject.com/KB/aspnet/aspnet_mvc_restapi.aspx的自定义ActionFilter。我如何在ASP.Net中测试自定义ActionFilter MVC

我想要一个使用http接受标头的自定义动作过滤器来返回JSON或Xml。一个典型的控制器动作将看起来像这样:

[AcceptVerbs(HttpVerbs.Get)] 
[AcceptTypesAttribute(HttpContentTypes.Json, HttpContentTypes.Xml)] 
public ActionResult Index() 
{ 
    var articles = Service.GetRecentArticles(); 

    return View(articles); 
} 

定制过滤器覆盖OnActionExecuted和将序列化对象(在此实例中的文章)作为JSON或XML。

我的问题是:我该如何测试?

  1. 我可以写什么样的测试?我是TDD新手,并不是100%确定我应该测试什么,测试什么。我想出了AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson()AcceptsTypeFilterXml_RequestHeaderAcceptsXml_ReturnsXml()AcceptsTypeFilter_AcceptsHeaderMismatch_ReturnsError406()
  2. 如何在测试Http Accept Headers的MVC中测试ActionFilter?

感谢。

回答

21

你只需要测试过滤器本身。只需创建一个实例并用测试数据调用OnActionExecuted()方法,然后检查结果。它有助于尽可能地分离代码。 Here's我写的一个例子。大部分繁重工作都在CsvResult班内完成,可以单独进行测试。您无需在实际控制器上测试过滤器。开展这项工作是MVC框架的责任。

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

我只是在this blog post这似乎是正确的方式给我迷迷糊糊中,他用Moq

编辑

好了,所以我们需要的这个第一章做的是嘲讽HTTPContext,也在请求中设置ContentType:

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

注 - 我没有自己测试过这个

+0

你能概括一下这里的要点吗? – 2015-08-19 07:50:46