我使用play 2.5开发了RESTful服务,我正在尝试为我的服务开发功能测试。我正在关注官方文件here。
以下是控制器的测试:
package com.x.oms.controller
import org.scalatestplus.play._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc.Action
import play.api.mvc.Results._
import play.api.routing.Router
import play.api.test.Helpers.{GET => GET_REQUEST}
class Test extends PlaySpec with OneServerPerSuite {
implicit override lazy val app =
new GuiceApplicationBuilder().router(Router.from {
// TODO: Find out how to load routes from routes file.
case _ => Action {
Ok("ok")
}
}).build()
"Application" should {
"be reachable" in {
// TODO: Invoke REST services using Play WS
// TODO: Assert the result
}
}
}
这是控制器:
package controllers.com.x.oms
import com.google.inject.Inject
import com.x.oms.AuthenticationService
import com.x.oms.model.DBModels.User
import com.x.oms.model.UIModels.Token
import play.api.Logger
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
class AuthenticationController @Inject()(as: AuthenticationService) extends Controller {
private val log = Logger(getClass)
def authenticate = Action(parse.json) {
request =>
val body = request.body
val username = (body \ "username").as[String]
val password = (body \ "password").as[String]
log.info(s"Attempting to authenticate user $username")
val token = as.authenticate(User(username, password))
log.debug(s"Token $token generated successfully")
token match {
case token: String => Ok(Json.toJson(new Token(token)))
case _ => Unauthorized
}
}
def logout = Action {
request =>
val header = request.headers
as.logout(header.get("token").get)
Ok("Logout successful")
}
def index = Action {
request =>
Ok("Test Reply")
}
}
路由文件:
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
POST /login controllers.com.x.oms.AuthenticationController.authenticate
POST /logout controllers.com.x.oms.AuthenticationController.logout
GET / controllers.com.x.oms.AuthenticationController.index
我不想在每次测试中重新定义路线信息。在每次测试中构建应用程序时,我需要您的帮助来加载路径文件。
请告诉我如何加载路径文件。提前致谢。
答案 0 :(得分:1)
我建议您在Play基础架构之外测试AuthenticationService
。如果您希望自己测试控制器,那么它们只是您可以使用FakeRequest
直接打电话的课程:
val api = new AuthenticationController(as)
"fail an authentication attempt with bad credentials" in {
val request = FakeRequest(POST, "/login")
.withJsonBody(jsonBadCredentials)
val result = call(api.authenticate(), request)
status(result) mustBe UNAUTHORIZED
}