正在测试的控制器操作:
[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
});
}
控制器的测试代码:想知道我需要做些什么来测试从控制器返回的Json:
[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);
}
答案 0 :(得分:7)
我首先要赞扬这篇文章: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);
希望这有助于或者至少为您提供一个跳跃点。