Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to unit test an Action method which returns JsonResult?
    text
    copied!<p>If I have a controller like this:</p> <pre><code>[HttpPost] public JsonResult FindStuff(string query) { var results = _repo.GetStuff(query); var jsonResult = results.Select(x =&gt; new { id = x.Id, name = x.Foo, type = x.Bar }).ToList(); return Json(jsonResult); } </code></pre> <p>Basically, I grab stuff from my repository, then project it into a <code>List&lt;T&gt;</code> of anonymous types.</p> <p>How can I unit-test it?</p> <p><code>System.Web.Mvc.JsonResult</code> has a property called <code>Data</code>, but it's of type <code>object</code>, as we expected.</p> <p>So does that mean if I want to test that the JSON object has the properties I expect ("id", "name", "type"), I have to use reflection?</p> <p><strong>EDIT:</strong></p> <p>Here's my test:</p> <pre><code>// 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."); } </code></pre> <p>But I get a runtime error in the loop, stating "object does not contain a definition for id". </p> <p>When I breakpoint, <code>actionResult.Data</code> is defined as a <code>List&lt;T&gt;</code> of anonymous types, so I figure if I enumerate through these, I can check the properties. Inside the loop, the object <strong>does</strong> have a property called "id" - so not sure what the issue is.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload