Asp.net-Mvc
如何在 ASP.Net MVC 中對自定義 ActionFilter 進行單元測試
因此,我正在創建一個主要基於此項目<http://www.codeproject.com/KB/aspnet/aspnet_mvc_restapi.aspx>的自定義 ActionFilter 。
我想要一個自定義操作過濾器,它使用 http 接受標頭返回 JSON 或 Xml。典型的控制器操作如下所示:
[AcceptVerbs(HttpVerbs.Get)] [AcceptTypesAttribute(HttpContentTypes.Json, HttpContentTypes.Xml)] public ActionResult Index() { var articles = Service.GetRecentArticles(); return View(articles); }自定義過濾器覆蓋 OnActionExecuted 並將對象(在本範例文章中)序列化為 JSON 或 Xml。
我的問題是:我該如何測試這個?
- 我要寫什麼測試?我是一名 TDD 新手,不能 100% 確定我應該測試什麼,不測試什麼。我想出了
AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson(),AcceptsTypeFilterXml_RequestHeaderAcceptsXml_ReturnsXml()和AcceptsTypeFilter_AcceptsHeaderMismatch_ReturnsError406()。- 如何在 MVC 中測試正在測試 Http Accept Headers 的 ActionFilter?
謝謝。
您只需要測試過濾器本身。只需創建一個實例並
OnActionExecuted()使用測試數據呼叫該方法,然後檢查結果。它有助於盡可能地將程式碼分開。大多數繁重的工作都在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); }