Leslie Hanks
Leslie Hanks

Reputation: 2377

How to get the actual JSON from a JsonResult object for a unit test?

I am wondering how I can take a JsonResult in a unit test and get the stringified JSON to validate it. I have seen ways to use dynamic types to verify the data, but I need to actually verify the data gets converted to strings appropriately.

Here is my code where I create it:

JsonResult result = new JsonResult {Data = new {EncryptedValue = value}};

The value object I am passing in is actually an type I wrote that can take a value (int, double, DateTime) and when cast to a string, it encrypts the value and I need to ensure that the JsonResult is casting it to a string correctly when stringifying.

Upvotes: 3

Views: 4173

Answers (3)

vvohra87
vvohra87

Reputation: 5674

You can do this in a number of ways, it is very possible.

This blog post has a very nice implementation of custom tests written and explained.

In this post the author uses a custom type which is being returned and does the same thing.

Upvotes: 1

Dmitry S.
Dmitry S.

Reputation: 8513

You would need to mock the HttpContext and ControllerContext for that. See the link below.

http://blogs.msdn.com/b/miah/archive/2009/02/25/unit-testing-the-mvc-jsonresult.aspx

Upvotes: 1

Related Questions