We’d like to test the response (using NUnit). We have a number of options here.
The ‘Correct’ (AKA long) way
This approach is how the MVC framework tests work. You can browse though it here. Here we are using Moq to mock out the HttpResponseBase and the ControllerContext. This allows us to grab what would normally be written to the HttpContext.Response and redirect into a StringBuilder object which we can interrogate later.
We are getting back a JsonResult.Data object. It is is still an anoymous object and has not yet been serialized by the HttpResponseBase object. The object looks like this:
rather than this:
Two approaches here. This first approach (much like the first test above) results in a pretty unreadable/unmaintainable test even providing your JsonResult.Data is small. It is very easy to get the string output wrong and cause a false failing test. It is quick and easy though.
We can so it using a much easier approach using RouteValueDictionary. I quite like this approach although it is a little counter intuitive to use the RouteValueDictionary class for accessing an anonymous type.
Finally, we can use dynamic. I much prefer the testing syntax of this approach but (there is always a ‘but’) there is an issue. JsonResult.Data is an anonymous type and these are, by default, declared as internal to their assembly and most tests are declared in a seperate project so no access to internal anonymous types in the controller assembly. By the time we get access to the JsonResult.Data we see it as an object.
If we run our test below, we will get a RuntimeBinderException exception 'object' does not contain a definition for 'Id.
Adding [assembly: InternalsVisibleTo("MyTestProject")] attribute on the web project AssemblyInfo.cs class (in the Properties folder) will allow our test to access the JsonResult.Data anonymous type. Re-run the test and all green.