Click here to Skip to main content
15,887,350 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
3.92/5 (7 votes)
13 Apr 2016CPOL 23.3K   2   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.

C#
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:

C#
    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.

C#
[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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Harshal Agarwal19-Apr-19 4:08
Harshal Agarwal19-Apr-19 4:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.