1

I'm trying to write some integration tests for an MVC application as follows

Controller

public JsonResult CreateWithJson(List<string> values) 
{
  if (values == null) return Json(new { Valid = false, Message = "No data was received by the server" });
}

Test Class

public static void TestEmptyDataFailsGracefully()
{
  var objUt = new MyController();
  var actual = objUt.CreateWithJson(new List<string>());

  actual.Should().BeOfType(typeof(JsonResult));

  // this is System.Object
  actual.Data...

  // what I want to do
  actual.Data.Valid.Should.Be(false);
}

So how do I query the anonymous type returned in the JsonResult please ?

SkeetJon
  • 1,491
  • 1
  • 19
  • 40
  • this might help :http://stackoverflow.com/questions/17232470/how-to-access-jsonresult-data-when-testing-in-asp-net-mvc – Ehsan Sajjad Apr 15 '16 at 08:27

1 Answers1

2

You will need to define type to which you want to deserialize JsonResult.

public class ValidationResults 
{
   bool Valid {get;set;}
   string Message {get;set;}
}

public JsonResult CreateWithJson(List<string> values) 
{
  if (values == null) return Json(new ValidationResults { Valid = false, Message = "No data was received by the server" });
}

public static void TestEmptyDataFailsGracefully()
{
  var objUt = new MyController();
  var actual = objUt.CreateWithJson(new List<string>());

  actual.Should().BeOfType(typeof(JsonResult));

  var serializer = new JavaScriptSerializer();
  var json = serializer.Serialize(actual.Data);
  ValidationResults validationResult = serializer.Deserialize<ValidationResults>(json);


  // what I want to do
  validationResult .Valid.Should.Be(false);
}
Nitin
  • 18,344
  • 2
  • 36
  • 53
  • thanks working perfectly; finding the reference for the test project: http://stackoverflow.com/questions/7000811/cannot-find-javascriptserializer-in-net-4-0 – SkeetJon Apr 15 '16 at 08:46