【发布时间】:2013-09-26 14:56:16
【问题描述】:
所以我有一个控制器,可以将 json 返回到我需要测试的视图中。我尝试使用具有动态数据类型的反射来访问列表的子属性,但我不断收到类似于“无法投射”错误的内容。基本上我在一个列表中有一个列表,我想访问和验证有关但我无法访问它的内容。有没有人在 MVC4 中测试过从他们的控制器返回的 json 并有建议?
代码:
// arrange
var repositoryMock = new Mock<IEdwConsoleRepository>();
var date = -1;
var fromDate = DateTime.Today.AddDays(date);
EtlTableHistory[] tableHistories =
{
new EtlTableHistory
{
Table = new Table(),
RelatedStatus = new BatchStatus(),
BatchId = 1
}
};
EtlBatchHistory[] batchHistories = { new EtlBatchHistory
{
Status = new BatchStatus(),
TableHistories = tableHistories
} };
repositoryMock.Setup(repository => repository.GetBatchHistories(fromDate)).Returns((IEnumerable<EtlBatchHistory>)batchHistories);
var controller = new EdwController(new Mock<IEdwSecurityService>().Object, repositoryMock.Object);
// act
ActionResult result = controller.BatchHistories(1);
// assert
Assert.IsInstanceOfType(result, typeof(JsonResult), "Result type was incorrect");
var jsonResult = (JsonResult)result;
var resultData = (dynamic)jsonResult.Data;
var returnedHistories = resultData.GetType().GetProperty("batchHistories").GetValue(resultData, null);
var returnedTableHistoriesType = returnedHistories.GetType();
Assert.AreEqual(1, returnedTableHistoriesType.GetProperty("Count").GetValue(returnedHistories, null), "Wrong number of logs in result data");
【问题讨论】:
-
我想从 batchHistories 中的 EtlBatchHistory 对象中获取“TableHistories”属性。
-
您的 JSON 是什么样的,和/或生成它的代码是什么?而且您应该能够只使用
var returnedHistories = resultData.batchHistories;,而无需反射(这就是dynamic的用途)。 (Count属性相同) -
Json 看起来像:“{ batchHistories = System.Collections.Generic.List
1[<>f__AnonymousType111[System.Int32,System.String,System.String,System.String,System.Int32,System. Nullable1[System.Int64],System.Nullable1[System.Int32],System.String,System.String,System.String,System.Collections.Generic.List1[<>f__AnonymousType09[System.String,System.String,System.Int32,System.Int32 ,System.String,System.String,System.String,System.String,System.String]]]] }" -
当我尝试直接从 resultData 访问 batchHistories 时,我得到一个 'object' does not contain a definition for 'batchHistories' 错误。
-
你的 JSON 不是很好的数据序列化。看起来您是通过在
List<T>上执行ToString()编写的。修复它。
标签: c# asp.net-mvc json unit-testing testing