Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have added a key-value pair in the action result like this:

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

I have some cumbersome codes like these in a 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 for me to fetch the value from that dictionary?

like image 660
Seen Avatar asked Dec 12 '22 14:12

Seen


1 Answers

Your FirstOrDefault isn't needed, because you'll get a NullReferenceException when accessing ErrorMessage. You can just use First().

Either way, I couldn't find any built-in solution. What I've done instead is create an extension method:

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

Which works like this:

ModelState.GetErrorMessageForKey("error");

If you need better exception handling, or support for multiple errors, its easy to extend...

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

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

and usage:

ViewData.GetModelStateError("error");
like image 106
Linkgoron Avatar answered May 16 '23 08:05

Linkgoron