使用Future和Json4s进行失败的scala测试

时间:2014-05-27 10:52:09

标签: scala future json4s

我有点疑惑为什么我的测试在引入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
}

1 个答案:

答案 0 :(得分:1)

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

val pony = service.getPony
val res = Await.result(pony, Duration("1 seconds"))
res must equalTo(SpecifiedPony)