C# 中的 TestMethod for JSON 数据检查来自 ASP .NET MVC 控制器

本文关键字:ASP NET MVC 控制器 检查 TestMethod 中的 for JSON 数据 | 更新日期: 2023-09-27 17:55:11

请告诉我如何通过不更改控制器操作来获取值。

Controller
     [HttpPost]
        public JsonResult A_Action_In_Controller(Guid ID)
        {
            var operationConfirmation = _repository.DoSomethingInDB(emailID);
            return Json(new { operationConfirmation }, JsonRequestBehavior.AllowGet);
        }
Test Method
    [TestMethod]
        public void DoSomethingInDB_SendOperationConfirmationToTheUI()
        {... 
                var expected = "Successfully Completed";
            var target = controller.A_Action_In_Controller(obj1.Id);
            Assert.AreEqual(expected, target.Data);
        }

错误

Assert.AreEqual failed. Expected:<Successfully Completed (System.String)>. Actual:<{ operationConfirmation = Successfully

已完成 } (<>f__AnonymousType2'1[[System.String, mscorlib, 版本=4.0.0.0,区域性=中性,公钥令牌=b77a5c561934e089]])>。

请告诉我如何写类似的东西 Assert.AreEqual(expected, target.Data.operationConfirmation);

而不是我现在拥有的,我不想更改我的控制器代码

Assert.AreEqual(expected, target.Data);

C# 中的 TestMethod for JSON 数据检查来自 ASP .NET MVC 控制器

控制器更改为

Controller
 [HttpPost]
    public JsonResult A_Action_In_Controller(Guid ID)
    {
        var operationConfirmation = _repository.DoSomethingInDB(emailID);
        return Json(operationConfirmation, JsonRequestBehavior.AllowGet);
    }

然后测试方法效果很好

  [TestMethod]
    public void DoSomethingInDB_SendOperationConfirmationToTheUI()
    {... var expected = "Operation failed";         

        var target = controller.A_Action_In_Controller(obj1.Id);
        Assert.AreEqual(expected, target.Data);

你需要反序列化 JSON 字符串,下面使用 JavaScriptSerializer 类:

首先,在A_Action_In_Controller方法中命名您的确认,如下所示:

return Json(new { confirmation = operationConfirmation }, JsonRequestBehavior.AllowGet);

然后在测试方法中执行此操作:

var js = new JavaScriptSerializer();
var deserializedTarget = (object[])js.DeserializeObject(target.Data.ToString());
var result = (string)deserializedTarget["confirmation"];

然后你可以做:

Assert.AreEqual(expected, result);