Unit Testing ASP.NET MVC4 Controller with Kendo

I am trying to unit test an ASP.NET MVC 4 controller that returns a Kendo.UI.Mvc DataSource result wrapped as Json. The problem is I can't get to the actual data returned .. it is always zero.

The question is how can I validate the JSON returning from the controller that wraps the Kendo.UI DataSourceResult.

+3


source to share


1 answer


This problem was pissed off because I could see the collection of data that I wanted in VS while debugging. I have updated the test equipment - it can be argued that these models can be executed.

I basically did the following:

  • Include ActionResult as JsonResult
  • Using a dynamic type, get "data" from the JsonResult returned by Kendo.Mvc.UI.DataSourceResult. Before using a dynamic type, only null was returned. (Note to yourself, learn more about dynamic type)
  • Pass the result from step 2 as the datatype you want to check.

Controller:



    public ActionResult EditRead([DataSourceRequest] DataSourceRequest request)
    {      
        return Json(GetViewModel().ToDataSourceResult(request));           
    }

      

Unit Test:

    [Test]
    public void EditRead_Should_Read_List_Or_Pharmacies()
    {
        //Create test db
        var db = new FakePharmacyDirectoryDb();
        db.AddSet(TestData.PharmacyLocations(10));

        //setup controller, we need to mock a DataSourceRequest
        //that Kendo.Mvc uses to communicate with the View
        var controller = new DirectoryController(db);
        var kendoDataRequest = new DataSourceRequest();

        //get the result back from the controller
        var controllerResult = controller.EditRead(kendoDataRequest);

        //cast the results to Json
        var jsonResult = controllerResult as JsonResult;

        //at runtime, jsonRsult.Data data will return variable of type Kendo.Mvc.UI.DataSourceResult
        dynamic kendoResultData = jsonResult.Data;

        //... which you can then cast DataSourceResult.Data as
        //the return type you are trying to test
        var results = kendoResultData.Data as List<PharmacyLocation>;

        Assert.IsInstanceOf<List<PharmacyLocation>>(results);
        Assert.AreEqual(10,results.Count);
    }

      

+5


source







All Articles