MVC TDD:如何编写 Response.Redirect 测试?
我是 MVC 和 TDD 的新手,所以如果这是一个愚蠢的问题,请饶恕我:)
我想做的是,我创建了一个 SignOn 控制器,我只想为该控制器编写一个测试。问题是 SignOn 控制器在内部执行 Response.Redirect,如果它是正确的请求,那么它可以正常工作,但是当我运行测试时,它会失败,因为没有响应对象。
那么我如何测试我的 SignOn 控制器,它在内部重定向?
I am new to MVC and TDD, so if it is a stupid question please spare me :)
What I am trying to do is , I have created a SignOn controller and I just want to write a Test for that controller. The thing is SignOn controller does Response.Redirect internally, that works fine if it is an proper request, but when I run my test it fails as there is no response object.
so how can I test my SignOn controller, which redirects internally ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您想要进行重定向时,您应该使用操作结果:
Redirect("url")
。在测试中,您可以检查 actionresult 的类型是否为 RedirectResult 和/或它是否具有正确的属性值。When you want to do a redirect you should use the actionresult:
Redirect("url")
. In your test you can check if the actionresult is of type RedirectResult and/or if it has the right property values.您的操作方法应返回 RedirectResult。如果您确切知道 URL 应该是什么,则可以测试
Url
属性。Your action method should return a RedirectResult. If you know exactly what the URL should be, you can test the
Url
property.我不是 TDD 人,但有件事告诉我 HttpContextBase 是你的朋友: http://msdn.microsoft.com/en-us/library/system.web.httpcontextbase.aspx
这里有一个很好的资源。
http://weblogs.asp.net/gunnarpeipman/archive/2011/07/16/using-moq-to-mock-asp-net-mvc-httpcontextbase.aspx
希望这有帮助。
I am not a TDD guy but something tells me that HttpContextBase is your friend : http://msdn.microsoft.com/en-us/library/system.web.httpcontextbase.aspx
Here is a good resource on that.
http://weblogs.asp.net/gunnarpeipman/archive/2011/07/16/using-moq-to-mock-asp-net-mvc-httpcontextbase.aspx
Hope this helps.
可用于在控制器/演示器内测试导航代码的模式之一是 ApplicationController。
看一下下面的描述PEAA:应用程序控制器
我们已经在 ASP 中实现了应用程序控制器。 NET应用程序。
ApplicationController 检查注册了哪些 NavigationWorkflow 并将导航分配到正确的类。
在单元测试中,您可以使用 rhino 模拟之类的东西来模拟 NavigationWorkflow,并将其传递给您的 ApplicationController。然后您可以检查工作流程中是否调用了正确的导航方法。
因此,您无需调用 Response.Redirect,而是将导航职责委托给可以用单元测试替换的单独类。
One of the patterns you can use for testing navigation code inside a controller/presenter is the ApplicationController.
Have a look at the following descriptionPEAA: Application Controller
We have implemented the Aplication Controller in our ASP.NET app.
The ApplicationController checks which NavigationWorkflows are registered and delagetes the navigation to the correct class.
In your unit tests you can mock the NavigationWorkflow with something like rhino mocks and pass this to your ApplicationController. Then you can check if the correct navigation methods are called on your workflow.
So instead of calling Response.Redirect, you delegate the navigation responsibility to a separate class that can be replaced with unit testing.