How to unit test an Action method which returns JsonResult?

前端 未结 8 1929
我在风中等你
我在风中等你 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: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));
    

提交回复
热议问题