title: Testing JSON Results from MVC 4 C# Controller
body: <p>So I have a controller that returns json to my views that I need to test. I have tried using reflection with a dynamic data type to access a sub property of a list but I keep getting something similar to 'unable to cast' errors. Basically I have a list within a list that I want to access and verify things about but I can't access it. Has anyone tested json returned from their controller before in MVC4 and have advice?</p>
  
  <p>Code:</p>
  
  <pre><code>// arrange
          var repositoryMock = new Mock&lt;IEdwConsoleRepository&gt;();
          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 =&gt; repository.GetBatchHistories(fromDate)).Returns((IEnumerable&lt;EtlBatchHistory&gt;)batchHistories);
          var controller = new EdwController(new Mock&lt;IEdwSecurityService&gt;().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");
  </code></pre>