How to Unit Test JsonResult and Collections in MSTest

mithun_daa picture mithun_daa · Nov 29, 2011 · Viewed 15.6k times · Source

I am very new to unit testing even though i have been coding for a very long time. I want to make this a part of my way of development. I run into blocks on how to unit test things like a collection. I generally have my jQuery script calling ASP.Net Server side methods to get data and populate tables and the like. They look like

Get_*Noun*() 

which generally returns a JsonResult. Any ideas on what and how to test these using Unit tests using MSTest?

Answer

David Ruttka picture David Ruttka · Dec 8, 2011

You should be able to test this just like anything else, provided you can extract the values from the JsonResult. Here's a helper that will do that for you:

private T GetValueFromJsonResult<T>(JsonResult jsonResult, string propertyName)
{
    var property =
        jsonResult.Data.GetType().GetProperties()
        .Where(p => string.Compare(p.Name, propertyName) == 0)
        .FirstOrDefault();

    if (null == property)
        throw new ArgumentException("propertyName not found", "propertyName");
    return (T)property.GetValue(jsonResult.Data, null);
}

Then call your controller as usual, and test the result using that helper.

var jsonResult = yourController.YourAction(params);
bool testValue = GetValueFromJsonResult<bool>(jsonResult, "PropertyName");
Assert.IsFalse(testValue);