3

I am trying to unit test an ASP.NET MVC 4 controller that is returning Kendo.UI.Mvc DataSource result wrapped as Json. The problem is that I cannot get to the returned the actual data .. it is always null.

The question is, how do I validate the JSON coming back from a Controller that wraps the Kendo.UI DataSourceResult.

4

1 回答 1

6

这个问题令人恼火,因为我可以在调试时在 VS 中看到我想要的数据集合。我已经更新了测试夹具 - 可以对模型数据执行断言。

基本上我做了以下事情:

  1. 将 ActionResult 转换为 JsonResult
  2. 使用动态类型,从返回 Kendo.Mvc.UI.DataSourceResult 的 JsonResult 中获取“数据”。在使用动态类型之前,仅返回 null。(注意自己,了解更多关于动态类型)
  3. 将 step2 的结果转换为您要测试的数据类型。

控制器:

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

单元测试:

    [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);
    }
于 2013-02-15T03:17:55.113 回答