如果我有这样的控制器:
[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);
}
Run Code Online (Sandbox Code Playgroud)
基本上,我从我的存储库中获取东西,然后将其投影到一个List<T>
匿名类型中.
我该如何对其进行单元测试?
System.Web.Mvc.JsonResult
有一个叫做的属性Data
,但它的类型object
,正如我们所期望的那样.
那么这是否意味着如果我想测试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 …
Run Code Online (Sandbox Code Playgroud)