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);
有帮助吗?

解决方案

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.

其他提示

dynamic:

dynamic testObject = YourMethodThatReturnsDynamicObject().Data;
Assert.AreEqual("OK", testObject.Status);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top