私がこのようなコントローラーを持っている場合:
[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
つまり、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」というプロパティがあります。そのため、問題が何であるかはわかりません。