Play 2反向路由,从控制器方法获取路由

6
使用Play 2.2.3框架,假设我在路由文件中有以下路由:
GET         /event                                 controllers.Event.events

我该如何通过编程的方式获取“/event”,已知我要访问的方法是 'controllers.Authentication.authenticate'?

我需要它进行测试,因为我想更好地等待测试,而不仅仅是路由本身,而是真正调用的控制器方法。所以也许有比现在获取路由并以此测试的另一种解决方案:

//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"
1个回答

25

按照以下方式构建反向路由:

[full package name].routes.[controller].[method]
在你的例子中:
 controllers.routes.Authentication.authenticate
 controllers.routes.Events.events

但是,假设您将包拆分为controllers.authcontrollers.content,那么它们将是:

 controllers.auth.routes.Authentication.authenticate
 controllers.content.routes.Events.events

反向路由返回一个包含 HTTP 方法和 URI 的 Call。在您的测试中,您可以使用 Call 构造一个 FakeRequest

 FakeRequest(controllers.routes.Authentication.authenticate)

您还可以使用它来测试重定向 URI:

 val call: Call = controllers.routes.Events.events 
 redirectLocation(loginResult) must beSome(call.url)

1
如果我正在使用 SIRD 路由器,它是如何工作的?在我的情况下,routes.conf 文件有 -> /ws/users WSRouters.UserRouterUserRouter 作为参数传递了 UserController,我正在调用 UserControllerverifyUser 方法。我该如何反向路由呢? - Manu Chadha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接