Access error message in ModelState error dictionary in ASP.net MVC unit test

I added a key-value pair to the result of the action:

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

I have some bulky codes like these in unit test to:

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

  }

Of course, it works whenever I have only one error.
I don't like facilities.ViewData.ModelState["Error"].Errors.FirstOrDefault().ErrorMessage .

Is there an easier way to get the value from this dictionary?

+4
source share
2 answers

Your FirstOrDefault is not required because when you access ErrorMessage you will get a NullReferenceException. You can just use First ().

In any case, I could not find a built-in solution. Instead, I created an extension method:

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

Which works as follows:

 ModelState.GetErrorMessageForKey("error"); 

If you need more efficient exception handling or support for multiple errors, it's easy to extend it ...

If you want this to be shorter, you can create an extension method for ViewData ...

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

and use:

 ViewData.GetModelStateError("error"); 
+12
source

Have you tried this?

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

Source: https://habr.com/ru/post/1347478/


All Articles