我有一个返回的方法
return new System.Web.Mvc.JsonResult() { Data = new { Status = "OK", } }我需要编写一个单元测试,以验证jsonResult.Data.status= "OK".
I need to write a unit test where I need to verify that jsonResult.Data.status= "OK".
如何读取状态属性?
更新: 我尝试了[assembly:InternalsVisibleTo("TestingAssemblyName")],但这没有帮助.我一直收到错误{'System.Web.Mvc.JsonResult'不包含'状态'的定义}
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);请注意,您将需要使用[InternalsVisibleTo]来使单元测试程序集对生产程序集中的匿名类型具有访问权限,因为匿名类型将通过internal访问权限生成.
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.
或者,只需使用反射.
更多推荐
如何读取匿名类型的属性?
发布评论