Asserting JsonResult Containing Anonymous Type

前端 未结 3 454
广开言路
广开言路 2021-02-05 00:51

I was trying to unit test a method in one of my Controllers returning a JsonResult. To my surprise the following code didn\'t work:

[HttpPost]
public JsonResult          


        
3条回答
  •  生来不讨喜
    2021-02-05 01:19

    Having read the responses here and then looking further afield I found a 2009 msdn blog post with a different approach again. But.. in the comments was a very simple and very elegant solution by Kieran ... to use .ToString().

    In your original case:

    [HttpPost]
    public JsonResult Test()
    {
        return Json(new {Id = 123});
    }
    

    You could test by doing:

    var jsonResult = controller.Test();
    Assert.AreEqual("{Id = 123}", jsonResult.Data.ToString());
    

    I much prefer this solution as it:

    • avoids changing the original code (InternalsVisibleTo, ExpandoObject),
    • avoids using MvcContrib and RhinoMocks (no issue with either of these but why add just to be able to test JsonResult?), and,
    • avoids using Reflection (adds complexity to the tests).

提交回复
热议问题