So I'm creating a custom ActionFilter that's based mostly on this project http://www.codeproject.com/KB/aspnet/aspnet_mvc_restapi.aspx.
I want a custom action filter that uses the http accept headers to return either JSON or Xml. A typical controller action will look like this:
[AcceptVerbs(HttpVerbs.Get)] [AcceptTypesAttribute(HttpContentTypes.Json, HttpContentTypes.Xml)] public ActionResult Index() { var articles = Service.GetRecentArticles(); return View(articles); }
The custom filter overrides the OnActionExecuted and will serialize the object (in this example articles) as either JSON or Xml.
My question is: how do I test this?
AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson()
, AcceptsTypeFilterXml_RequestHeaderAcceptsXml_ReturnsXml()
and AcceptsTypeFilter_AcceptsHeaderMismatch_ReturnsError406()
.Thanks.
To unit test an action filter, you have to pass in an action filter context object (which requires a lot of setup). Action filter methods are void, so you have to verify the behavior by inspecting the context object (or dependencies, like a logger, if you are injecting those).
thanks! unit tests do not run in the "MVC environment." They will run within the scope of the test runner, be that nunit, resharper,....
You just need to test the filter itself. Just create an instance and call the OnActionExecuted()
method with test data then check the result. It helps to pull the code apart as much as possible. Most of the heavy lifting is done inside the CsvResult
class which can be tested individually. You don't need to test the filter on an actual controller. Making that work is the MVC framework's responsibility.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With