加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在ASP.Net MVC中对自定义ActionFilter进行单

发布时间:2020-12-16 00:03:34 所属栏目:asp.Net 来源:网络整理
导读:所以我正在创建一个主要基于此项目 http://www.codeproject.com/KB/aspnet/aspnet_mvc_restapi.aspx的自定义ActionFilter. 我想要一个自定义操作过滤器,它使用http接受标头返回JSON或Xml.典型的控制器操作如下所示: [AcceptVerbs(HttpVerbs.Get)][AcceptTyp
所以我正在创建一个主要基于此项目 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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读