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)
{
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