Search code examples
c#anonymous-typesjsonresult

How to read a property of an anonymous type?


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

Solution

  • 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.