0

我有点困惑为什么我的测试在引入 json4s 解析时失败了。应用程序本身可以正常工作。

申请代码:

import org.json4s.native.JsonMethods

class PonyService {

  protected def client = new PonyClient // Returns Future[String]

  def getPony(): Future[Pony] = {
    val contentFuture = client.retrieveContent()
    contentFuture.map{case s => extractPony(s)}
  }

  def getPonyJSON(): Future[String] = {
    val contentFuture = client.retrieveContent()
    contentFuture.map{case s => s}
  }

  def extractPony(json: String): Pony = {
    implicit val formats = DefaultFormats
    (parse(json) \ "result").extract[Pony]
  }
}

测试代码:

val mockClient = mock[PonyClient]
mockClient.retrieveContent() returns Future.successful {"pony json here"}

val service = new PonyService {
  override protected def client = mockClient
}

whenReady(service.getPony()) {
  r => r must equalTo(SpecifiedPony) // Fail - A timeout occurred waiting for a future to complete.
}

whenReady(service.getPonyJSON()) {
  r => r must equalTo("pony json here") // Success
}
4

1 回答 1

1

事实证明,在 whenReady 中等待的时间太短了。例如,这很好用:

val pony = service.getPony
val res = Await.result(pony, Duration("1 seconds"))
res must equalTo(SpecifiedPony)
于 2014-05-27T13:04:14.163 回答