Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Unit Test the JSon Result in MVC Unit Test Case

0.00/5 (No votes)
13 Apr 2016 1  
How to unit test the JSon result

Introduction

Once you are writing a unit test case for your MVC controller, sometimes, you face the issue if the controller return type is JSON AS in the given example.

I have created a method SearchRecords in MVC controller. You can write your logic in the code.

public JsonResult SearchRecords(GridSettings gridSettings)
{

//....Your code logic here

//....

return Json(jsonData, JsonRequestBehavior.AllowGet);

}

Here, I am taking an input parameter as gridSettings. You can take or create any method which just returns the type as JsonResult.

Using the Code

The JSon data which I will retrieve on our view will be as follows:

    var jsonData = new{
total = 6
page = 1,
records = 51
};

Now, in the unit test case where I will test this result in very simple way.

[TestMethod]
   public void GetData()
   {
       IMAPDataAccess objDataAccess = new MAPDataAccess();
       GridSettings gridSettings = new GridSettings();

       var controller = new YourControllerName(objDataAccess);
       gridSettings.IsSearch = false;
       gridSettings.PageIndex = 1;
       gridSettings.PageSize = 10;

       var result = controller.SearchData(gridSettings) as JsonResult;

   IDictionary<string, object> data =
   (IDictionary<string, object>)new System.Web.Routing.RouteValueDictionary(result.Data);

       Assert.AreEqual(1, data["page"]);
       Assert.AreEqual(51, data["records"]);
       Assert.AreEqual(6, data["total"]);
   }

Points of Interest

In this way, you can normally write the unit test case for json return type instead of using json data in Assert.AreEqual.

History

  • 13th April, 2016: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here