2017-06-13 19 views
1

在編寫本文時,Play 2.6處於候選版本狀態。 的Action單已被棄用,因此,所有有關測試這裏的信息已經過時:如何在Play 2.6中單元測試服務器現在已棄用Action單例

https://www.playframework.com/documentation/2.6.0-RC2/ScalaTestingWebServiceClients

即使用DSL的模擬服務器的路由,像這樣:

Server.withRouter() { 
    case GET(p"/repositories") => Action { 
    Results.Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World"))) 
    } 
} { implicit port => ... 

導致廢棄警告。

有沒有辦法規避這個問題,還是我們只需要等待他們更新他們的測試DSL?

回答

0

是的,有一種新的方法可以在Play框架2.6中使用ScalaTest進行此操作。您需要使用Guice來構建Application並注入您自己的RouterProvider。考慮這個例子:

class MyServiceSpec 
    extends PlaySpec 
    with GuiceOneServerPerTest { 

    private implicit val httpPort = new play.api.http.Port(port) 

    override def newAppForTest(testData: TestData): Application = 
    GuiceApplicationBuilder() 
     .in(Mode.Test) 
     .overrides(bind[Router].toProvider[RouterProvider]) 
     .build() 

    def withWsClient[T](block: WSClient => T): T = 
    WsTestClient.withClient { client => 
     block(client) 
    } 

    "MyService" must { 

    "do stuff with an external service" in { 
     withWsClient { client => 
     // Create an instance of your client class and pass the WS client 
     val result = Await.result(client.getRepositories, 10.seconds) 
     result mustEqual List("octocat/Hello-World") 
     } 
    } 
    } 
} 

class RouterProvider @Inject()(action: DefaultActionBuilder) extends Provider[Router] { 
    override def get: Router = Router.from { 
    case GET(p"/repositories") => action { 
     Results.Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World"))) 
    } 
    } 
}