How To Test JsonResult in ASP.NET MVC

Published 28/03/2016 - Updated 27/07/2023

A profile picture of Gary Lewis Cheetham, the author of this article

Written by

Gary Lewis Cheetham

Automotive marketing specialist from Manchester, UK

Table of Contents [Show]

    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.

    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.

    About the author

    A profile picture of Gary Lewis Cheetham, the founder of GL Digital Automotive Marketing, smiling outside a car dealership

    Gary Lewis Cheetham is an automotive marketing specialist, born and raised in Oldham, Greater Manchester. Gary Lewis Cheetham is the founder of GL Digital Automotive Marketing. He spent his teenage years working at the family dealership after school, learning the ropes of the car trade from the inside out.

    After moving on to working in marketing, Gary Lewis founded GL Digital in 2020 when he noticed a need for direct-to-consumer marketing platforms within the auto industry. He now strives every day to help independent dealers in the UK and US realise their potential. Gary also loves Formula 1 and motorsport.