“动态”关键字和 JSON 数据
我的 ASP.NET MVC2 应用程序中的操作方法返回一个 JsonResult 对象,在我的单元测试中,我想检查返回的 JSON 对象是否确实包含预期值。
我尝试了这个:
1. dynamic json = ((JsonResult)myActionResult).Data;
2. Assert.AreEqual(JsonMessagesHelper.ErrorLevel.ERROR.ToString(), json.ErrorLevel);
但我得到一个 RuntimeBinderException“'object' 不包含 'ErrorLevel' 的定义”。
但是,当我在第 2 行放置断点并检查 json 动态变量(参见下图)时,它显然确实包含 ErrorLevel 字符串并且它具有预期值,因此如果运行时绑定程序不是'不要开玩笑,测试就会通过。
我没有得到什么?我做错了什么以及如何解决这个问题?我怎样才能让断言通过?
An action method in my ASP.NET MVC2 application returns a JsonResult object and in my unit test I would like to check that the returned JSON object indeed contains the expected values.
I tried this:
1. dynamic json = ((JsonResult)myActionResult).Data;
2. Assert.AreEqual(JsonMessagesHelper.ErrorLevel.ERROR.ToString(), json.ErrorLevel);
But I get a RuntimeBinderException "'object' does not contain a definition for 'ErrorLevel'".
However, when I place a breakpoint on line 2 and inspect the json dynamic variable (see picture below), it obviously does contain the ErrorLevel string and it has the expected value, so if the runtime binder wasn't playing funny the test would pass.
What am I not getting? What am I doing wrong and how can I fix this? How can I make the assertion pass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你真的不需要动态。这是一个例子。假设您想要对以下操作进行单元测试:
以及相应的测试:
您还可能会发现 以下博客文章很有用。
You don't really need dynamic. Here's an example. Suppose you had the following action which you would like to unit test:
and the corresponding test:
Also you might find the following blog post useful.
JsonResult
的Data
属性的类型为Object
这意味着,尽管您有动态声明,但设置的类型仍然是>对象
。另一个问题是您使用匿名类型作为Data
,然后尝试将其作为适用范围之外的声明实例进行访问。使用 @Darin 的技术通过 RouteValueDictionary 访问属性值。The
Data
property of theJsonResult
is of typeObject
this means, although you have a dynamic declaration, the type that is set is stillObject
. The other issue is that you are using an anonymous type as theData
and then trying to access that as a declared instance outside of its applicable scope. Use @Darin's technique for accessing the property values using aRouteValueDictionary
.