这个问题令人恼火,因为我可以在调试时在 VS 中看到我想要的数据集合。我已经更新了测试夹具 - 可以对模型数据执行断言。
基本上我做了以下事情:
- 将 ActionResult 转换为 JsonResult
- 使用动态类型,从返回 Kendo.Mvc.UI.DataSourceResult 的 JsonResult 中获取“数据”。在使用动态类型之前,仅返回 null。(注意自己,了解更多关于动态类型)
- 将 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);
}