如何对返回JsonResult的Action方法进行单元测试?

如果我有这样的控制器:
[HttpPost]
public JsonResult FindStuff(string query) 
{
   var results = _repo.GetStuff(query);
   var jsonResult = results.Select(x => new
   {
      id = x.Id,
      name = x.Foo,
      type = x.Bar
   }).ToList();

   return Json(jsonResult);
}
基本上,我从我的存储库中获取东西,然后将其投影到一个匿名类型的
List<T>
。 我该如何对其进行单元测试?
System.Web.Mvc.JsonResult
有一个名为
Data
的属性,但它的类型为
object
,正如我们所料。 那么这是否意味着如果我想测试JSON对象具有我期望的属性(“id”,“name”,“type”),我必须使用反射? 编辑: 这是我的测试:
// Arrange.
const string autoCompleteQuery = "soho";

// Act.
var actionResult = _controller.FindLocations(autoCompleteQuery);

// Assert.
Assert.IsNotNull(actionResult, "No ActionResult returned from action method.");
dynamic jsonCollection = actionResult.Data;
foreach (dynamic json in jsonCollection)
{
   Assert.IsNotNull(json.id, 
       "JSON record does not contain "id" required property.");
   Assert.IsNotNull(json.name, 
       "JSON record does not contain "name" required property.");
   Assert.IsNotNull(json.type, 
       "JSON record does not contain "type" required property.");
}
但是我在循环中得到一个运行时错误,说明“对象不包含id的定义”。 当我断点时,
actionResult.Data
被定义为匿名类型的
List<T>
,所以我想如果我通过这些枚举,我可以检查属性。在循环内部,对象确实有一个名为“id”的属性 - 所以不确定问题是什么。     
已邀请:
RPM,你看起来是正确的。我还有很多东西可以学习
dynamic
,我也无法让Marc的方法工作。所以我以前是这样做的。你会发现它很有用。我刚写了一个简单的扩展方法:
    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);
    }
然后我只是用它来对我的Json数据做断言:
        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));
    
我知道我对这些人有点迟,但我发现为什么动态解决方案不起作用:
JsonResult
返回一个匿名对象,默认情况下为
internal
,因此需要使它们对测试项目可见。   打开ASP.NET MVC应用程序项目,从名为Properties的文件夹中找到
AssemblyInfo.cs
。打开AssemblyInfo.cs并将以下行添加到此文件的末尾。
[assembly: InternalsVisibleTo("MyProject.Tests")]
引用自:http://weblogs.asp.net/gunnarpeipman/archive/2010/07/24/asp-net-mvc-using-dynamic-type-to-test-controller-actions-returning-jsonresult.aspx 我认为将这一个用于记录会很好。奇迹般有效     
我参加派对有点晚了,但是我创建了一个小包装器,然后让我使用
dynamic
属性。在这个答案中,我已经开始使用ASP.NET Core 1.0 RC2了,但我相信如果用
resultObject.Data
替换
resultObject.Value
,它应该适用于非核心版本。
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;
    }
}
用法,假设以下控制器:
public class FooController : Controller
{
    public IActionResult Get()
    {
        return Json(new {Bar = "Bar", Baz = "Baz"});
    }
}
测试(xUnit):
// Arrange
var controller = new FoosController();

// Act
var result = await controller.Get();

// Assert
var resultObject = Assert.IsType<JsonResult>(result);
dynamic resultData = new JsonResultDynamicWrapper(resultObject);
Assert.Equal("Bar", resultData.Bar);
Assert.Equal("Baz", resultData.Baz);
    
我从Matt Greer扩展解决方案并提出这个小扩展:
    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;
    }
我只是运行unittest: - 设置预期的数据结果:
        var expected = new
        {
            Success = false,
            Message = "Name is required"
        };
- 断言结果:
        // Assert
        result.IsJson().WithModel(expected);
    
这是我使用的一个,也许对任何人都有用。它测试一个返回JSON对象的操作,以便在客户端功能中使用。它使用Moq和FluentAssertions。
[TestMethod]
public void GetActivationcode_Should_Return_JSON_With_Filled_Model()
{
    // Arrange...
    ActivatiecodeController activatiecodeController = this.ActivatiecodeControllerFactory();
    CodeModel model = new CodeModel { Activation = "XYZZY", Lifespan = 10000 };
    this.deviceActivatieModelBuilder.Setup(x => x.GenereerNieuweActivatiecode()).Returns(model);

    // Act...
    var result = activatiecodeController.GetActivationcode() as JsonResult;

    // Assert...
    ((CodeModel)result.Data).Activation.Should().Be("XYZZY");
    ((CodeModel)result.Data).Lifespan.Should().Be(10000);
}
    
我的解决方案是编写扩展方法:
using System.Reflection;
using System.Web.Mvc;

namespace Tests.Extensions
{
    public static class JsonExtensions
    {
        public static object GetPropertyValue(this JsonResult json, string propertyName)
        {
            return json.Data.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public).GetValue(json.Data, null);
        }
    }
}
    
如果在测试中你知道Json数据的确切结果应该是什么,那么你可以这样做:
result.Data.ToString().Should().Be(new { param = value}.ToString());
附:如果你使用过FluentAssertions.Mvc5就行了 - 但是把它转换成你使用的测试工具应该不难。     

要回复问题请先登录注册