如何在ASP.NET MVC测试时访问JsonResult数据 [英] How to access JsonResult data when testing in ASP.NET MVC

查看:136
本文介绍了如何在ASP.NET MVC测试时访问JsonResult数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#MVC控制器这个code:

I have this code in C# mvc Controller:

[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() });
        }
    }

我如何访问我的JSON的错误字段中ControllerTest来检查它是否是空或不是?

How I can access my Json "error" field in a ControllerTest to check if it is null or not?

[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); 是我想做些什么。有任何想法吗?谢谢你。

Assert.IsNotNull(result.Data.error); is what I would like to do. Any Ideas? Thanks.

推荐答案

您可以使用这样,结果将有望对象定义。所以,如果OD的成功,你的成功标志是TRUE否则为false,如果假的,那么你应该预料到的错误属性与错误信息进行更新。

you can use like this , Result will be expected object definition . So in case od success , your success flag will be TRUE otherwise false and if false then you should expect that error property is updated with the error message.

        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;
        }

这篇关于如何在ASP.NET MVC测试时访问JsonResult数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆