How to read a property of an anonymous type?
Asked Answered
A

2

12

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);
Assumed answered 20/12, 2012 at 22:15 Comment(3)
In a MS Unit Test or Javascript?Jewel
If you are doing this from C#, you could just use dynamic and let the dynamic binder take care of it.Teofilateosinte
gallio unit test. What I am trying is Assert.AreEqual("OK", jsonResult.Data.Status)Assumed
G
18

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.

Gutturalize answered 20/12, 2012 at 22:18 Comment(0)
A
8

dynamic:

dynamic testObject = YourMethodThatReturnsDynamicObject().Data;
Assert.AreEqual("OK", testObject.Status);
Anastomose answered 20/12, 2012 at 22:19 Comment(3)
The expected value should be the first argument to AreEqual, and the actual value should be the second.Gutturalize
@JonSkeet .. there you go, although as I was typing it I just didn't think (sometimes intellisense goes a long way!).Anastomose
@ AnonymousVoter: I appreciate the sympathy vote.. difficult to get any when you reply at the same time as Jon! :)Anastomose

© 2022 - 2024 — McMap. All rights reserved.