玩2个反向路由,从控制器方法获取路由 [英] Play 2 reverse routing, get route from controller method
问题描述
使用 Play 2.2.3 框架,因为我的路由文件中有这样的路由:
Using the Play 2.2.3 framework, given I have a route like this one in my routes file :
GET /event controllers.Event.events
如何以编程方式获取/event",知道我试图达到的方法,在这种情况下是 'controllers.Authentication.authenticate' ?
How can I programatically get the "/event" knowing the method I am trying to reach, in this case 'controllers.Authentication.authenticate' ?
我需要它用于测试目的,因为我希望有更好的测试,而不是等待路由本身,而是等待真正调用的控制器方法.因此,也许还有另一种解决方案,而不是像我现在那样获取路线并以这种方式进行测试:
I need it for test purpose, because I would like to have better test waiting not for the route itself but for the controllers method really called. So maybe there is another solution than getting the route and test it this way like I do for now :
//Login with good password and login
val Some(loginResult) = route(FakeRequest(POST, "/login").withFormUrlEncodedBody(
("email", email)
, ("password", password)))
status(loginResult)(10.seconds) mustBe 303
redirectLocation(loginResult).get mustBe "/event"
推荐答案
你这样构造反向路由:
[full package name].routes.[controller].[method]
在你的例子中:
controllers.routes.Authentication.authenticate
controllers.routes.Events.events
但是如果你像 controllers.auth
和 controllers.content
一样把你的包分开,那么它们会是:
But say you broke your packages out like controllers.auth
and controllers.content
, then they would be:
controllers.auth.routes.Authentication.authenticate
controllers.content.routes.Events.events
反向路由返回一个 Call
,其中包含一个 HTTP 方法和 URI.在您的测试中,您可以使用 Call
构造一个 FakeRequest
:
The reverse routes return a Call
, which contains an HTTP method and URI. In your tests you can construct a FakeRequest
with a Call
:
FakeRequest(controllers.routes.Authentication.authenticate)
你也可以用它来测试重定向 URI:
And you can also use it to test the redirect URI:
val call: Call = controllers.routes.Events.events
redirectLocation(loginResult) must beSome(call.url)
这篇关于玩2个反向路由,从控制器方法获取路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!