Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 585
juanchoelx Avatar asked Jun 21 '13 10:06

juanchoelx


People also ask

How do I assert JsonResult?

We can return jsonResult via invoking the Josn() method in the controller, in general, I will pass one anonymous object such as Josn(new {isSuccess = true, message="It's success!"}); var actionResult = controller. JosnMethod() as JsonResult; Assert.

How can we pass the data from controller to view in MVC?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

What is the use of JsonResult in MVC?

JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON) format. In this article, I will explain how to access the data from a JsonResult object and display it in a browser with an example.

What is the difference between ActionResult and JsonResult?

Use JsonResult when you want to return raw JSON data to be consumed by a client (javascript on a web page or a mobile client). Use ActionResult if you want to return a view, redirect etc to be handled by a browser.


2 Answers

You can use like this - the result will be the expected object definition. So in case of success, your success flag will be TRUE otherwise false and if false then you should expect that the error property will be 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;
        }
like image 93
Devesh Avatar answered Sep 27 '22 22:09

Devesh


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 in different assemblies, you need to make the test assembly a "friend" assembly of the controller assembly, like this:

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

like image 41
ttacompu Avatar answered Sep 27 '22 22:09

ttacompu