我该如何进行单元测试在ASP.Net MVC自定义ActionFilter [英] How do I unit test a custom ActionFilter in ASP.Net MVC

查看:193
本文介绍了我该如何进行单元测试在ASP.Net MVC自定义ActionFilter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建一个自定义ActionFilter说的大多是基于这个项目<一个href=\"http://www.$c$cproject.com/KB/aspnet/aspnet_mvc_restapi.aspx\">http://www.$c$cproject.com/KB/aspnet/aspnet_mvc_restapi.aspx.

So I'm creating a custom ActionFilter that's based mostly on this project http://www.codeproject.com/KB/aspnet/aspnet_mvc_restapi.aspx.

我想使用http接受头部返回JSON或XML格式的自定义操作过滤器。一个典型的控制器动作看起来就像这样:

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

在自定义过滤器覆盖OnActionExecuted并将序列化对象(本例中的文章)作为JSON或XML。

The custom filter overrides the OnActionExecuted and will serialize the object (in this example articles) as either JSON or Xml.

我的问题是:我如何测试这个


  1. 测试什么我写?我是一个新手TDD和我不是100%肯定,我应该是什么样的测试,什么不进行测试。我想出了 AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson() AcceptsTypeFilterXml_RequestHeaderAcceptsXml_ReturnsXml() AcceptsTypeFilter_AcceptsHeaderMismatch_ReturnsError406()

  2. 如何测试MVC中的ActionFilter正在测试中的HTTP头接受?

感谢。

推荐答案

您只需要测试过滤器本身。只需创建一个实例,并调用 OnActionExecuted()法测试数据然后检查结果。它有助于除了尽可能多地拉code。 <一href=\"https://github.com/g0t4/DotNetExtensions/blob/master/UiConventions/src/UiConventions/TableResult/TableFilterAttribute.cs\">Here's一个例子,我已经写了。最繁重的工作是在 CsvResult 可单独测试类来完成。不需要测试一个实际控制在过滤器上。做这项工作是MVC框架的责任。

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. Here's an example I've written. 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);
}

这篇关于我该如何进行单元测试在ASP.Net MVC自定义ActionFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆