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調用,我會喜歡聽到吧:)
的感謝!