Testing JsonResults in ASP.NET MVC
Posted on October 23, 2008I needed a way to test values in a JsonResult to verify an action was behaving properly. In my action i return something like this:
public JsonResult DoSomething(){
//do stuff here
return new JsonResult {
Data = {
success = true,
message = "Yay, it worked!"
}
};
}
| |
1
2
3
4
5
6
7
8
9
|
So in my test for the Action i need to verify the values of success and message but they're in an anonymous type so I need to pluck out the values. That's where this extension method comes into play:
public static T Value<T>(this JsonResult jsonResult, string propertyName)
{
T result = default(T);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(jsonResult.Data);
PropertyDescriptor prop = props.Find(propertyName, true);
result = (T)prop.GetValue(jsonResult.Data);
return result;
}
| |
1
2
3
4
5
6
7
8
|
Now in my test I can do stuff like this:
JsonResult json = controller.DoSomething();
Assert.IsTrue(json.Value<bool>("success"));
Assert.AreEqual("Yay, it worked!", json.Value<string>("message"));
| |
1
2
3
|
Pretty cool, huh?