How to unit test an Action method which returns JsonResult?

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

    I'm a bit late to the party, but I created a little wrapper that lets me then use dynamic properties. As of this answer I've got this working on ASP.NET Core 1.0 RC2, but I believe if you replace resultObject.Value with resultObject.Data it should work for non-core versions.

    public class JsonResultDynamicWrapper : DynamicObject
    {
        private readonly object _resultObject;
    
        public JsonResultDynamicWrapper([NotNull] JsonResult resultObject)
        {
            if (resultObject == null) throw new ArgumentNullException(nameof(resultObject));
            _resultObject = resultObject.Value;
        }
    
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (string.IsNullOrEmpty(binder.Name))
            {
                result = null;
                return false;
            }
    
            PropertyInfo property = _resultObject.GetType().GetProperty(binder.Name);
    
            if (property == null)
            {
                result = null;
                return false;
            }
    
            result = property.GetValue(_resultObject, null);
            return true;
        }
    }
    

    Usage, assuming the following controller:

    public class FooController : Controller
    {
        public IActionResult Get()
        {
            return Json(new {Bar = "Bar", Baz = "Baz"});
        }
    }
    

    The test (xUnit):

    // Arrange
    var controller = new FoosController();
    
    // Act
    var result = await controller.Get();
    
    // Assert
    var resultObject = Assert.IsType(result);
    dynamic resultData = new JsonResultDynamicWrapper(resultObject);
    Assert.Equal("Bar", resultData.Bar);
    Assert.Equal("Baz", resultData.Baz);
    

提交回复
热议问题