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

前端 未结 3 1691
北海茫月
北海茫月 2020-12-17 18:02

I have this code in C# mvc Controller:

[HttpPost]
    public ActionResult Delete(string runId)
    {
        if (runId == \"\" || runId == null)
                 


        
相关标签:
3条回答
  • 2020-12-17 18:12

    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;
            }
    
    0 讨论(0)
  • 2020-12-17 18:13

    If you returned an actually non-anonymous class, you could have just done:

    var strongTypedResult = result as <YourStrongTypeHere>;

    0 讨论(0)
  • 2020-12-17 18:18

    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")]

    0 讨论(0)
提交回复
热议问题