Có một fix for the integrated approach to this trong Playframewrk v2.1 Tôi có một backport of the fix on the 2.0.x branch
Cho đến khi nó được sáp nhập và phát hành, đây là những gì tôi đã làm (nó hoạt động trên Play 2.0.3+):
Tôi đã định nghĩa đối tượng Helpers của chính mình trong một gói libs như vậy.
package libs
import play.api.mvc._
import play.api.libs.iteratee._
import play.api.libs.concurrent._
import play.api.test._
object Helpers {
def routeAndCall[T](request: FakeRequest[T]): Option[Result] = {
routeAndCall(this.getClass.getClassLoader.loadClass("Routes").asInstanceOf[Class[play.core.Router.Routes]], request)
}
/**
* Use the Router to determine the Action to call for this request and executes it.
*/
def routeAndCall[T, ROUTER <: play.core.Router.Routes](router: Class[ROUTER], request: FakeRequest[T]): Option[play.api.mvc.Result] = {
val routes = router.getClassLoader.loadClass(router.getName + "$").getDeclaredField("MODULE$").get(null).asInstanceOf[play.core.Router.Routes]
routes.routes.lift(request).map {
case a: Action[_] =>
val action = a.asInstanceOf[Action[T]]
val parsedBody: Option[Either[play.api.mvc.Result, T]] = action.parser(request).fold(
(a, in) => Promise.pure(Some(a)),
k => Promise.pure(None),
(msg, in) => Promise.pure(None)
).await.get
parsedBody.map{resultOrT =>
resultOrT.right.toOption.map{innerBody =>
action(FakeRequest(request.method, request.uri, request.headers, innerBody))
}.getOrElse(resultOrT.left.get)
}.getOrElse(action(request))
}
}
}
Sau đó, trong thử nghiệm của tôi, tôi nhập Helpers của tôi và toàn thể Helpers chơi bối cảnh, ngoại trừ routeAndCall:
import libs.Helpers._
import play.api.test.Helpers.{routeAndCall => _,_}
sau đó tôi sử dụng một khoảng để thiết lập ứng dụng của tôi (tôi cần cung cấp một ứng dụng. bí mật như tôi lưu trữ tên chứng thực người dùng trong phiên giao dịch mà là dựa trên một cookie ký)
def appWithSecret():Map[String,String]={
Map(("application.secret","the answer is 42 !"))
}
object emptyApp extends Around {
def around[T <% Result](t: => T) = {
running(FakeApplication(additionalConfiguration = inMemoryMongoDatabase("emptyApp")++appWithSecret())) {
User(new ObjectId, "Jane Doe", "[email protected]", "id1").save()
t // execute t inside a http session
}
}
}
này cho phép tôi để viết các bài kiểm tra sau:
"respond to the index Action" in emptyApp {
val request: FakeRequest[AnyContent] = FakeRequest(GET, "/expenses").withSession(("email", "[email protected]"))
val Some(result) = routeAndCall(request)
status(result) must equalTo(OK)
contentType(result) must beSome("application/json")
charset(result) must beSome("utf-8")
contentAsString(result) must contain("Hello Bob")
}
Nó cho phép bạn thực hiện mã bảo mật mặc dù nó không phải là một thử nghiệm đơn vị.