【问题标题】:Access the error message in ModelState error dictionary in ASP.net MVC unit test在 ASP.net MVC 单元测试中访问 ModelState 错误字典中的错误消息
【发布时间】:2011-08-02 18:07:36
【问题描述】:

我在动作结果中添加了一个键值对,如下所示:

[HttpPost,授权] 公共 ActionResult ListFacilities(int countryid) { ... ModelState.AddModelError("Error","该国家无设施报告!"); ... }

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

公共无效 ShowFailforFacilities() { //虚假数据 var facility = controller.ListFacilities(1) as PartialViewResult; Assert.AreSame("在这个国家没有报告设施!", facility.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage); }

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

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

【问题讨论】:

    标签: asp.net-mvc unit-testing nunit modelstate


    【解决方案1】:

    不需要您的 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");
    

    【讨论】:

    【解决方案2】:

    你试过了吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多