2016-12-05 30 views
2

我使用play 2.5開發了RESTful服務,我正在嘗試爲我的服務開發功能測試。我正在關注官方文檔here功能測試使用scalatest播放服務

下面是控制器的測試:

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 

我不想重新定義路線每個測試中的信息。在每次測試中構建應用程序時,我需要您的幫助來加載路線文件。

請讓我知道如何加載路由文件。提前致謝。

回答

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 
} 
+0

您的解決方案工作!儘管我必須添加WithApplication進行測試。謝謝你的幫助。 – Ravi

+0

有幾種方法可以實現這一點。鑑於我看到你在使用DI,我會讓我的測試擴展PlaySpec,OneAppPerSuite(也許還有其他一些如果你認爲有用),你可以通過GuiceApplicationBuilder創建你的應用程序,然後使用DI注入器來設置你的環境。 – andyczerwonka