How To Test JsonResult in ASP.NET MVC
Published 28/03/2016 - Updated 27/07/2023
Table of Contents
Here’s a quick NuGet of wisdom! (Haha, just kidding, there is no wisdom in NuGet)
Writing a unit test for an ActionResult Json()
is a bit of a head-scratcher for some, but all it requires is a simple cast operation.
Example controller:
public ActionResult Index()
{
return Json(productsData, JsonRequestBehavior.AllowGet);
}
Example test: (NUnit 3.x)
[Test]
public void GetActionReturnsProductsAsJson()
{
var mockProductsData = new List<IProduct> { /* ... */ };
productsController.setData(mockProductsData);
JsonResult result = productsController.Index() as JsonResult;
Assert.That(
result.Data as List<IProduct>,
Is.EqualTo(mockProductsData));
}
There are two casts going on here:
- The first cast (
productsController.Index() as JsonResult
) makes sure that we’re dealing with a JsonResult in the test and not an ActionResult. - The second cast
result.Data as List<IProduct>
takes theData
property of theJsonResult
and casts it to aList
ofIProduct
that we can compare against our mock data.
Note that you could have achieved the same thing using the alternative cast syntax:
JsonResult result = (JsonResult)productsController.Index();
But the as
keyword is preferred, because it will return null
instead of an exception if the cast is not possible.
Expert advice
You're reading the GL Digital blog, where auto marketing experts share proven tactics to grow your dealership.
Struggling to make good video?
Sometimes it feels like posting on TikTok is a waste of time.
Build a powerful local brand and watch customers roll in from TikTok.