3

The controller action being tested:

    [AuthorizeUser]
    [HttpPost]
    [ValidateJsonAntiForgeryToken]
    public ActionResult EventDetails(int eventId)
    {
        string details = this._eventDataProvider.GetById(eventId).Comments;

        if (string.IsNullOrEmpty(details))
            details = "This location has not entered any comments or further details for this event.";

        return Json(new
        {
            details = details
        });
    }

Test code for the controller: wondering what I need to do to test the Json being returned from the controller:

    [TestMethod]
    public void DetailsAreReturned()
    {
        // Arrange
        eventsController = new EventsController(eventDataProvider.Object, playerEventDataProvider.Object, userDataProvider.Object,
                                                tokenAuthent.Object, dataContext.Object, customerLocationDataProvider.Object);

        eventDataProvider.Setup(x => x.GetById(1)).Returns(new Event() { Comments = "test" });

        // Act
        JsonResult result = (JsonResult) eventsController.EventDetails(1);

        // Assert
        Assert.IsNotNull(result.Data);

        Assert.AreEqual(??, result);
    }
Nick B
  • 657
  • 1
  • 13
  • 33

1 Answers1

9

I have to give credit to this post first: How do I iterate over the properties of an anonymous object in C#?

var result = new JsonResult{ Data = new {details = "This location has not entered any comments or further details for this event."}};

var det = result.Data.GetType().GetProperty("details", BindingFlags.Instance | BindingFlags.Public);

var dataVal = det.GetValue(result.Data, null);

Hope this helps or at least gives you a jumping point.

Community
  • 1
  • 1
ermagana
  • 1,090
  • 6
  • 11