小编典典

在ASP.NET MVC中进行测试时如何访问JsonResult数据

json

我在C#mvc控制器中有以下代码:

[HttpPost]
    public ActionResult Delete(string runId)
    {
        if (runId == "" || runId == null)
        {
            return this.Json(new { error = "Null or empty params" });
        }
        try
        {
            int userId = (int)Session["UserId"];
            int run = Convert.ToInt32(runId);

            CloudMgr cloud = new CloudMgr(Session);
            cloud.DeleteRun(userId, run);

            return this.Json(new { success = true });
        }
        catch (Exception ex)
        {
            return this.Json(new { error = ex.ToString() });
        }
    }

如何在ControllerTest中访问我的Json“错误”字段以检查其是否为null?

[TestMethod]
    public void DeleteWrongParam()
    {
        WhatIfController controller = new WhatIfController();
        controller.ControllerContext = 
        TestUtils.CreateMockSessionControllerContext().Object as ControllerContext;

        JsonResult result = controller.DeleteWhatIf(null) as JsonResult;

Assert.IsNotNull(result.Data.error);是我想做的。有任何想法吗?谢谢。


阅读 393

收藏
2020-07-27

共1个答案

小编典典

您可以这样使用-
结果将是预期的对象定义。因此,在成功的情况下,您的成功标志将为TRUE,否则为false,如果为false,那么您应该期望error属性将随错误消息更新。

        JsonResult jsonResult = oemController.List() as JsonResult;
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Result result = serializer.Deserialize<Result>(serializer.Serialize(jsonResult.Data));

        public class Result 
        {
            public bool success ;
            public string error;
        }
2020-07-27