播放2个反向路由,从控制器方法获取路由 [英] Play 2 reverse routing, get route from controller method

查看:45
本文介绍了播放2个反向路由,从控制器方法获取路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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

我如何以编程方式知道我要尝试的方法(在本例中为"controllers.Authentication.authenticate"),以获取"/event"?

How can I programatically get the "/event" knowing the method I am trying to reach, in this case 'controllers.Authentication.authenticate' ?

出于测试目的,我需要它,因为我希望有更好的测试,而不是等待路由本身,而是等待真正调用的controllers方法.因此,也许还有别的解决方案,而不是像现在一样以这种方式进行测试:

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"

推荐答案

您可以通过以下方式构造反向路由:

You construct the reverse route in this way:

[full package name].routes.[controller].[method]

在您的示例中:

 controllers.routes.Authentication.authenticate
 controllers.routes.Events.events

但是说您将包分解为controllers.authcontrollers.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆