How To Test ASP.Net MVC JsonResult

Posted almost 2 years ago on April 17, 2010

Testing the result of an ASP.Net MVC controller action that returns an anonymous type can be difficult. This task is made difficult by the fact that the framework serializes the return value under the covers before it gets returned to the client.

Capture

On the unit test side, I don’t have anything to cast that anonymous type to so I can get at it’s contents.

The best and most simple way (so far) that I’ve found to accomplish this goal is to use a class from the System.Web.Extensions DLL called System.Web.Script.Serialization.JavaScriptSerializer.

Here’s a simple test to demonstrate:

Capture

Please let me know if you know of a better way to perform this verification.

Comments

Schotime writes...

I wouldn't test the actual output, cause then you are testing the serializer. I would just test the values that are returned.

April 25, 2010

Steve Horn writes...

@Schotime

How do you propose I "...just test the values that are returned."

There is no easy way (that I know of) to reach inside an anonymous object to validate the data.

April 25, 2010

Stefano Martinz writes...

you could use dynamics:

dynamic result = _pieController.SomeMethod();

Assert.That(result.Data.something, Is ...

Just remember to make the assembly you're testing InternalsVisibleTo. ie add to its AssemblyInfo.cs:

[assembly:InternalsVisibleTo("TestAssembly")]

July 23, 2010

Tim writes...

I agree with Schotime. I believe if you just test the values returned then you will be able to validate your synchronizer.

September 13, 2010

New Comment