【问题标题】:Querying JsonResult in C# integration tests在 C# 集成测试中查询 JsonResult
【发布时间】:2016-08-07 02:51:52
【问题描述】:

我正在尝试为 MVC 应用程序编写一些集成测试,如下所示

控制器

public JsonResult CreateWithJson(List<string> values) 
{
  if (values == null) return Json(new { 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));

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

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

请问JsonResult中返回的匿名类型如何查询呢?

【问题讨论】:

标签: c# asp.net-mvc anonymous-types


【解决方案1】:

您需要定义要反序列化的类型 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);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-07-07
  • 2014-03-19
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 2022-11-11
相关资源
最近更新 更多