How to read a property of an anonymous type?

2020-08-12 16:14发布

问题:

I have a method that returns

return new  System.Web.Mvc.JsonResult()
{                     
    Data = new
    {
        Status = "OK", 
    }
}

I need to write a unit test where I need to verify that jsonResult.Data.status= "OK".

How do I read the status property?

Update: I tried the [assembly: InternalsVisibleTo("TestingAssemblyName")], but that didn't help. I kept getting the error {"'System.Web.Mvc.JsonResult' does not contain a definition for 'Status'"}

Besides I think I will prefer not modifying the code that I am testing.

So I took Jon's advice and used reflection.

        var type = jsonResult.Data.GetType();

        var pinfo = type.GetProperty("Status");

        string  statusValue = pinfo.GetValue(jsonResult.Data,null).ToString();

        Assert.AreEqual("OK", statusValue);

回答1:

The simplest approach would probably be to use dynamic typing:

dynamic foo = ret.Data;
Assert.AreEqual("OK", foo.status);

Note that you'll need to use [InternalsVisibleTo] in order to give your unit test assembly access to the anonymous type in your production assembly, as it will be generated with internal access.

Alternatively, just use reflection.



回答2:

dynamic:

dynamic testObject = YourMethodThatReturnsDynamicObject().Data;
Assert.AreEqual("OK", testObject.Status);