How To Test JsonResult in ASP.NET MVC

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 the Data property of the JsonResult and casts it to a List of IProduct 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.