1 min read

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)

    public void GetActionReturnsProductsAsJson()
        var mockProductsData = new List<IProduct> { /* ... */ };
        JsonResult result = productsController.Index() as JsonResult;
            result.Data as List<IProduct>,

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.

Join the Adstronauts 🪐

Talk is cheap, online advertising isn't. Every week I'll send you actionable tips to grow your Shopify business.

No spam ever. Unsubscribe anytime.