“动态”关键字和 JSON 数据

发布于 2024-10-11 03:18:58 字数 568 浏览 1 评论 0原文

我的 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 字符串并且它具有预期值,因此如果运行时绑定程序不是'不要开玩笑,测试就会通过。

Locals 调试器窗口的快照

我没有得到什么?我做错了什么以及如何解决这个问题?我怎样才能让断言通过?

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.

Snapshot of the Locals debugger window

What am I not getting? What am I doing wrong and how can I fix this? How can I make the assertion pass?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半衬遮猫 2024-10-18 03:18:58

你真的不需要动态。这是一个例子。假设您想要对以下操作进行单元测试:

public ActionResult Index()
{
    return Json(new { Id = 5, Foo = "bar" });
}

以及相应的测试:

// act
var actual = subjectUnderTest.Index();

// assert
var data = new RouteValueDictionary(actual.Data);
Assert.AreEqual(5, data["Id"]);
Assert.AreEqual("bar", data["Foo"]);

您还可能会发现 以下博客文章很有用。

You don't really need dynamic. Here's an example. Suppose you had the following action which you would like to unit test:

public ActionResult Index()
{
    return Json(new { Id = 5, Foo = "bar" });
}

and the corresponding test:

// act
var actual = subjectUnderTest.Index();

// assert
var data = new RouteValueDictionary(actual.Data);
Assert.AreEqual(5, data["Id"]);
Assert.AreEqual("bar", data["Foo"]);

Also you might find the following blog post useful.

沙与沫 2024-10-18 03:18:58

JsonResultData 属性的类型为 Object 这意味着,尽管您有动态声明,但设置的类型仍然是 >对象。另一个问题是您使用匿名类型作为Data,然后尝试将其作为适用范围之外的声明实例进行访问。使用 @Darin 的技术通过 RouteValueDictionary 访问属性值。

The Data property of the JsonResult is of type Object this means, although you have a dynamic declaration, the type that is set is still Object. The other issue is that you are using an anonymous type as the Data 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 a RouteValueDictionary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文