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

Seen picture Seen · Apr 11, 2011 · Viewed 9.3k times · Source

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?

Answer

Linkgoron picture Linkgoron · Apr 11, 2011

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