读取 RedirectToRouteResult 的 RouteValues 字典

发布于 2025-01-08 06:45:28 字数 1071 浏览 1 评论 0原文

我正在学习 ASP MVC,因此对 TDD 和 MVC 框架很陌生。我在编写模拟 TestMethod 用于测试控制器内的操作(​​其主体中的“RedirectToAction”)时发现一个问题。

编写testMethod以确保重定向的Action是正确的。我读到可以检查 RedirectToRouteResult.RouteValues,并获取“action”键的值。即使在调试中(观察属性)我也能得到正确的结果。但是@编译时测试显示异常Cannot apply Indexing with [] to an expression of type RedirectToRouteResult.RouteValues

以下是供参考的代码片段:

public void TestHomeControllerContactRedirectRoute()
        {
            HomeController controller = new HomeController();
            ContactMessage message=new ContactMessage(){

                Email="[email protected]",
                MessageBody="Some message here!!",
                Name="Sun"
            };

            RedirectToRouteResult resultRoute = controller.Contact(message) as RedirectToRouteResult;

            if (resultRoute != null)
            {

                Assert.AreEqual("Contact", resultRoute.RouteValues["action"]);
            }
        }

I am learning ASP MVC , thus new to TDD and MVC frameworks. I find an issue while writing mock TestMethod for testing a Action inside the Controller, that " RedirectToAction" in its body.

Writing the testMethod to make sure the redirected Action is correct. I read it's possible to check with RedirectToRouteResult.RouteValues, and getting value for "action" key. Even in debug (watching down to the properties) I am able to get it correct. But @ compile time the test is showing exception Cannot apply Indexing with [] to an expression of type RedirectToRouteResult.RouteValues.

Following is the code snippet for the reference:

public void TestHomeControllerContactRedirectRoute()
        {
            HomeController controller = new HomeController();
            ContactMessage message=new ContactMessage(){

                Email="[email protected]",
                MessageBody="Some message here!!",
                Name="Sun"
            };

            RedirectToRouteResult resultRoute = controller.Contact(message) as RedirectToRouteResult;

            if (resultRoute != null)
            {

                Assert.AreEqual("Contact", resultRoute.RouteValues["action"]);
            }
        }

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

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

发布评论

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

评论(1

热血少△年 2025-01-15 06:45:28

可能缺少对 System.Web 源的引用

http://samritchie.net/2011/01 /06/mvc-单元测试-错误/

Potentially missing a reference to System.Web

Source: http://samritchie.net/2011/01/06/mvc-unit-testing-error/

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