[asp.net] asp.net mvc 에서 테스트시 jsonResult 에 접근하는 방법

Posted by RAY.D
2015. 4. 27. 14:12 Web/ASP.NET MVC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.




How to access JsonResult data when testing in ASP.NET MVC


http://stackoverflow.com/questions/17232470/how-to-access-jsonresult-data-when-testing-in-asp-net-mvc



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

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); is what I would like to do. Any Ideas? Thanks.









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





JavaScriptSerializer is good for string and static type. Here you created anonymous type as Json(new { success = true }). This case, you had better used dynamic type.

JsonResult result = controller.DeleteWhatIf(null) as JsonResult;
dynamic dresult = result.Data;
Assert.IsTrue(dresult.succes);

You need to import Microsoft.CSharp dll to test project. If test and your controller are different assembly, you need to make friend assembly from controller assembly.

[assembly: InternalsVisibleTo("testproject assembly name")]