chris carter's web log

Home |  Contact |  Admin
 

Testing JsonResults in ASP.NET MVC

Posted on October 23, 2008

I 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?

Huh, There's a Windows 7 Blog

Posted on October 23, 2008

Finally, Notebooks with 3+ GHz processors

Posted on October 23, 2008

Well specifically thinkpads.  I'm liking where the W series is going.  17 inch monitor, which I'm still on the fence.  1 gig dedicated frickin video card.  And now you can get a 64 gig SSD as the primary and a zippy 7200rpm secondary drive.  Now, if only I could get it all for half of the price....or win the lottery.  My only request is that Windows 7 ships before I get stuck upgrading to Vista..

Check out the specs: