How to unit test an Action method which returns JsonResult?

前端 未结 8 1922
我在风中等你
我在风中等你 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<JsonResult>(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);
    
    0 讨论(0)
  • 2020-12-13 13:12

    RPM, you look to be correct. I still have much to learn about dynamic and I cannot get Marc's approach to work either. So here is how I was doing it before. You may find it helpful. I just wrote a simple extension method:

        public static object GetReflectedProperty(this object obj, string propertyName)
        {  
            obj.ThrowIfNull("obj");
            propertyName.ThrowIfNull("propertyName");
    
            PropertyInfo property = obj.GetType().GetProperty(propertyName);
    
            if (property == null)
            {
                return null;
            }
    
            return property.GetValue(obj, null);
        }
    

    Then I just use that to do assertions on my Json data:

            JsonResult result = controller.MyAction(...);
                        ...
            Assert.That(result.Data, Is.Not.Null, "There should be some data for the JsonResult");
            Assert.That(result.Data.GetReflectedProperty("page"), Is.EqualTo(page));
    
    0 讨论(0)
提交回复
热议问题