[asp.net] asp.net mvc 에서 테스트시 jsonResult 에 접근하는 방법
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")]
'Web > ASP.NET MVC' 카테고리의 다른 글
[asp.net] 데이터 삭제후에 MVC에서 페이지 reload 하기 (2) | 2015.04.27 |
---|---|
[asp.net] jsonResult 객체 로 부터 json 을 얻는 방법 (2) | 2015.04.27 |
[asp.net] view 에서 controller 로 json 객체를 파라미터로서 넘기는 방법 (630) | 2015.04.27 |
[asp.net] json 문자를 json 객체로 파싱 (2) | 2015.04.27 |
[asp.net] json 의 serialize(시리얼라이즈) / deserialize(디시리얼라이즈) 하기 (2) | 2015.04.27 |