2017-03-29 40 views
0

我在我的項目中有一個服務類,我想測試其執行api調用的方法之一,所以我想抓住這個調用和返回的東西假的,所以我可以測試我的方法,它看起來像這樣:獲取方案java.lang.NullPointerException:試圖僞造我的服務中的服務器調用時的方案

class MyService @Inject()(implicit config: Configuration, wsClient: WSClient) { 

    def methodToTest(list: List[String]): Future[Either[BadRequestResponse, Unit]] = { 
    wsClient.url(url).withHeaders(("Content-Type", "application/json")).post(write(list)).map { response => 
     response.status match { 
     case Status.OK => 
      Right(logger.debug("Everything is OK!")) 
     case Status.BAD_REQUEST => 
      Left(parse(response.body).extract[BadRequestResponse]) 
     case _ => 
      val ex = new RuntimeException(s"Failed with status: ${response.status} body: ${response.body}") 
      logger.error(s"Service failed: ", ex) 
      throw ex 
     } 
    } 
    } 
} 

,現在在我的測試類,我去:

class MyServiceTest extends FreeSpec with ShouldMatchers with OneAppPerSuite with ScalaFutures with WsScalaTestClient { 

    implicit lazy val materializer: Materializer = app.materializer 
    lazy val config: Configuration = app.injector.instanceOf[Configuration] 
    lazy val myService = app.injector.instanceOf[MyService] 

    "My Service Tests" - { 

    "Should behave as im expecting" in { 
     Server.withRouter() { 
     case POST(p"/fake/api/in/conf") => Action { request => 
      Results.Ok 
     } 
     } { implicit port => 
     WsTestClient.withClient { implicit client => 

      whenReady(myService.methodToTest(List("1","2","3"))) { res => 
      res.isRight shouldBe true 
      } 
     } 
     } 
    } 
    } 
} 

,我得到這個錯誤:

scheme java.lang.NullPointerException: scheme 

也試圖在客戶端=>提出:

val myService = new MyService { 
     implicit val config: Configuration = configuration 
     implicit val ws: WSClient = client 
     } 

,但得到的是我不在構造函數中有足夠的論據其他一些錯誤......

它爲什麼不工作?

如果有假的更好次簡單的方法此API調用,我會喜歡聽到吧:)

的感謝!

回答

1

Server.withRouter可能不是你想要的。它創建一個服務器並將其綁定到每個實例的隨機端口(除非您指定端口)。它還會創建自己的應用程序實例,該應用程序將從您用於實例化服務的應用程序中斷開斷開

另一件事是,注入的WSClient不要工作相對於您的應用程序。您需要使用傳遞給WsTestClient.withClient塊的client。所以,你應該這樣做:

class MyServiceTest extends FreeSpec with ShouldMatchers with OneAppPerSuite with ScalaFutures with WsScalaTestClient { 

    implicit lazy val materializer: Materializer = app.materializer 
    lazy val config: Configuration = app.injector.instanceOf[Configuration] 

    "My Service Tests" - { 

    "Should behave as im expecting" in { 
     Server.withRouter() { 
     case POST(p"/fake/api/in/conf") => Action { request => 
      Results.Ok 
     } 
     } { implicit port => 
     WsTestClient.withClient { implicit client => 

      // Use the client "instrumented" by Play. It will 
      // handle the relative aspect of the url. 
      val myService = new MyService(client, config) 

      whenReady(myService.methodToTest(List("1","2","3"))) { res => 
      res.isRight shouldBe true 
      } 
     } 
     } 
    } 
    } 
}