2011-12-14 72 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