How to read a property of an anonymous type?

泪湿孤枕 提交于 2019-12-06 20:16:07

问题


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);


来源:https://stackoverflow.com/questions/13981429/how-to-read-a-property-of-an-anonymous-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!