How to unit test an Action method which returns JsonResult?

前端 未结 8 1925
我在风中等你
我在风中等你 2020-12-13 12:38

If I have a controller like this:

[HttpPost]
public JsonResult FindStuff(string query) 
{
   var results = _repo.GetStuff(query);
   var jsonResult = results         


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 13:11

    I extend the solution from Matt Greer and come up with this small extension:

        public static JsonResult IsJson(this ActionResult result)
        {
            Assert.IsInstanceOf(result);
            return (JsonResult) result;
        }
    
        public static JsonResult WithModel(this JsonResult result, object model)
        {
            var props = model.GetType().GetProperties();
            foreach (var prop in props)
            {
                var mv = model.GetReflectedProperty(prop.Name);
                var expected = result.Data.GetReflectedProperty(prop.Name);
                Assert.AreEqual(expected, mv);
            }
            return result;
        }
    

    And i just run the unittest as this: - Set the expected data result:

            var expected = new
            {
                Success = false,
                Message = "Name is required"
            };
    

    - Assert the result:

            // Assert
            result.IsJson().WithModel(expected);
    

提交回复
热议问题