An original idea from this answer with a more general approach. Using a custom DynamicObject as a wrapper to check the value through reflection, there was no need to add InternalsVisibleTo
public class DynamicObjectResultValue : DynamicObject, IEquatable<DynamicObjectResultValue> { private readonly object value; public DynamicObjectResultValue(object value) { this.value = value; } #region Operators public static bool operator ==(DynamicObjectResultValue a, DynamicObjectResultValue b) {
Assuming the following controller
public class FooController : Controller { public IActionResult GetAnonymousObject() { var jsonResult = new { id = 1, name = "Foo", type = "Bar" }; return Ok(jsonResult); } public IActionResult GetAnonymousCollection() { var jsonResult = Enumerable.Range(1, 20).Select(x => new { id = x, name = "Foo" + x, type = "Bar" + x }).ToList(); return Ok(jsonResult); } }
Tests may look like
[TestMethod] public void TestDynamicResults() { //Arrange var controller = new FooController(); //Act var result = controller.GetAnonymousObject() as OkObjectResult; //Assert dynamic obj = new DynamicObjectResultValue(result.Value); Assert.IsNotNull(obj); Assert.AreEqual(1, obj.id); Assert.AreEqual("Foo", obj.name); Assert.AreEqual(3, obj.name.Length); Assert.AreEqual("Bar", obj.type); } [TestMethod] public void TestDynamicCollection() { //Arrange var controller = new FooController(); //Act var result = controller.GetAnonymousCollection() as OkObjectResult; //Assert Assert.IsNotNull(result, "No ActionResult returned from action method."); dynamic jsonCollection = result.Value; foreach (dynamic value in jsonCollection) { dynamic json = new DynamicObjectResultValue(value); 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."); } }
Nkosi
source share