在ASP.net MVC单元测试中访问ModelState错误字典中的错误消息

4
我已经在操作结果中添加了一个键值对,如下所示:
[HttpPost, Authorize]
public ActionResult ListFacilities(int countryid)
{
...
    ModelState.AddModelError("Error","该国家没有报告任何设施!");
...
}
我在单元测试中有一些繁琐的代码,如下所示:
public void ShowFailforFacilities()
{
    //虚假数据
    var facilities = controller.ListFacilities(1) as PartialViewResult;
Assert.AreSame("该国家没有报告任何设施!", facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage);
}
当然,只有一个错误时它是有效的。
我不喜欢 facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage
是否有更简单的方法来从那个字典中获取值?
2个回答

13

你的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");

参见https://dev59.com/c2Mm5IYBdhLWcg3wfu82 - Alexey
如何从ASP.NET MVC ModelState获取所有错误 - Alexey

0

你试过这个吗?

// Note: In this example, "Error" is the name of your model property.
facilities.ViewData.ModelState["Error"].Value
facilities.ViewData.ModelState["Error"].Error

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接