如果我有这样的控制器:
[HttpPost]
public JsonResult FindStuff(string query)
{
var results = _repo.GetStuff(query);
var jsonResult = results.Select(x => new
{
id = x.Id,
name = x.Foo,
type = x.Bar
}).ToList();
return Json(jsonResult);
}
基本上,我从我的存储库中获取东西,然后将其投影到List<T>
匿名类型中。
我怎样才能对它进行单元测试?
System.Web.Mvc.JsonResult
有一个名为 的属性Data
,但object
正如我们预期的那样,它是 type 。
那么这是否意味着如果我想测试 JSON 对象是否具有我期望的属性(“id”、“name”、“type”),我必须使用反射?
编辑:
这是我的测试:
// Arrange.
const string autoCompleteQuery = "soho";
// Act.
var actionResult = _controller.FindLocations(autoCompleteQuery);
// Assert.
Assert.IsNotNull(actionResult, "No ActionResult returned from action method.");
dynamic jsonCollection = actionResult.Data;
foreach (dynamic json in jsonCollection)
{
Assert.IsNotNull(json.id,
"JSON record does not contain \"id\" required property.");
Assert.IsNotNull(json.name,
"JSON record does not contain \"name\" required property.");
Assert.IsNotNull(json.type,
"JSON record does not contain \"type\" required property.");
}
但是我在循环中遇到运行时错误,指出“对象不包含 id 的定义”。
当我断点时,actionResult.Data
被定义为List<T>
匿名类型,所以我想如果我枚举这些,我可以检查属性。在循环内部,该对象确实有一个名为“id”的属性 - 所以不确定问题是什么。