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

asp.net-mvc – 在ASP.net MVC单元测试中访问ModelState错误字典

发布时间:2020-12-16 07:31:44 所属栏目:asp.Net 来源:网络整理
导读:我在动作结果中添加了一个键值对,如下所示: [HttpPost,Authorize] public ActionResult ListFacilities(int countryid){... ModelState.AddModelError("Error","No facilities reported in this country!");...} 我在单元测试中有一些像这样繁琐的代码: pu
我在动作结果中添加了一个键值对,如下所示:

[HttpPost,Authorize]
        public ActionResult ListFacilities(int countryid)
{
...
        ModelState.AddModelError("Error","No facilities reported in this country!");
...
}

我在单元测试中有一些像这样繁琐的代码:

 public void ShowFailforFacilities()
 {
    //bogus data
    var facilities = controller.ListFacilities(1) as PartialViewResult;


    Assert.AreSame("No facilities reported in this country!",facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage);

 }

当然,只要我有一个错误,它就可以工作.
我不喜欢facilities.ViewData.ModelState [“Error”].Errors.FirstOrDefault().ErrorMessage.

我是否有更简单的方法从该字典中获取值?

解决方法

不需要FirstOrDefault,因为访问ErrorMessage时会出现NullReferenceException.你可以使用First().

无论哪种方式,我都找不到任何内置的解决方案.我所做的是创建一个扩展方法:

public static class ExtMethod
    {
        public static string GetErrorMessageForKey(this ModelStateDictionary dictionary,string key)
        {
            return dictionary[key].Errors.First().ErrorMessage;
        }
    }

其工作方式如下:

ModelState.GetErrorMessageForKey("error");

如果您需要更好的异常处理或支持多个错误,它很容易扩展…

如果您希望缩短它,可以为ViewData创建一个扩展方法…

public static class ExtMethod
    {
        public static string GetModelStateError(this ViewDataDictionary viewData,string key)
        {
            return viewData.ModelState[key].Errors.First().ErrorMessage;
        }
    }

和用法:

ViewData.GetModelStateError("error");

(编辑:李大同)

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

    推荐文章
      热点阅读