2017-02-01 53 views
0

我使用playframework 2.2.6 scala。MockServer在org.specs2測試中

我想爲我的應用程序編寫集成測試。但我的應用程序通過http請求一些服務,我想用mockServer來模擬它。但我不知道什麼時候開始和停止mockServer原因試驗利用期貨

@RunWith(classOf[JUnitRunner]) 
class AppTest extends Specification with Around { 

    def around[T](t: => T)(implicit e: AsResult[T]): Result = { 

     val port = 9001 

     val server = new MockServer() 

     server.start(port, null) 

     val mockServerClient = new MockServerClient("127.0.0.1", port) 

     // mockServerClient rules 

     val result = AsResult.effectively(t) 

     server.stop() 

     result 
    } 

    "Some test" should { 

     "some case" in new WithApplication { 

      val request: Future[SimpleResult] = route(...).get 

      status(request) must equalTo(OK) 

      contentAsString(request) must contain(...) 
     } 

     "some other case" in new WithApplication { 
      // 
     } 
    } 
} 

有了這個代碼,我有java.net.ConnectException:連接被拒絕:/127.0.0.1:9001。如果沒有server.stop,我不能這樣做,因爲服務器必須在不同的測試中運行。

+0

更換in new WithApplication你可以嘗試用而不是「圍繞每個人」的特質?當你想要在每個例子周圍執行行爲時,這是一個特性。然後,如果你想檢查期貨,通常可以使用'contains(...)。await',前提是你在範圍內有一個隱含的'ExecutionEnv':'AppTest(隱式ee:ExecutionEnv)extends AroundEach'。如果它適合你,我會把它變成一個答案。 – Eric

回答

0

我找到了解決辦法,我看着WithApplication的源代碼(它周圍擴展),並寫了抽象類WithMockServer:

abstract class WithMockServer extends WithApplication { 

    override def around[T: AsResult](t: => T): Result = { 

    Helpers.running(app) { 

     val port = Play.application.configuration.getInt("service.port").getOrElse(9001) 
     val server = new MockServer(port) 

     val mockServerClient = new MockServerClient("127.0.0.1", port) 

     // mockServer rules 

     val result = AsResult.effectively(t) 
     server.stop() 
     result 
    } 
    } 
} 

而且在每次測試情況下,我與in new WithMockServer

相關問題