15

我有一个简单的喷雾客户端:

val pipeline = sendReceive ~> unmarshal[GoogleApiResult[Elevation]]

val responseFuture = pipeline {Get("http://maps.googleapis.com/maps/api/elevation/jsonlocations=27.988056,86.925278&sensor=false") }

responseFuture onComplete {
  case Success(GoogleApiResult(_, Elevation(_, elevation) :: _)) =>
    log.info("The elevation of Mt. Everest is: {} m", elevation)
    shutdown()

  case Failure(error) =>
    log.error(error, "Couldn't get elevation")
    shutdown()
}

完整的代码可以在这里找到。

我想模拟服务器的响应来测试SuccessFailure案例中的逻辑。我找到的唯一相关信息是这里,但我无法使用蛋糕模式来模拟 sendReceive 方法。

任何建议或示例将不胜感激。

4

2 回答 2

19

这是使用 specs2 进行测试规范和 mockito 进行模拟的一种模拟方法的示例。首先,该Main对象被重构为一个用于模拟的类设置:

class ElevationClient{
  // we need an ActorSystem to host our application in
  implicit val system = ActorSystem("simple-spray-client")
  import system.dispatcher // execution context for futures below
  val log = Logging(system, getClass)

  log.info("Requesting the elevation of Mt. Everest from Googles Elevation API...")

  import ElevationJsonProtocol._
  import SprayJsonSupport._

  def sendAndReceive = sendReceive

  def elavation = {
    val pipeline = sendAndReceive ~> unmarshal[GoogleApiResult[Elevation]]

    pipeline {
      Get("http://maps.googleapis.com/maps/api/elevation/json?locations=27.988056,86.925278&sensor=false")
    }   
  }


  def shutdown(): Unit = {
    IO(Http).ask(Http.CloseAll)(1.second).await
    system.shutdown()
  }
}

然后,测试规范:

class ElevationClientSpec extends Specification with Mockito{

  val mockResponse = mock[HttpResponse]
  val mockStatus = mock[StatusCode]
  mockResponse.status returns mockStatus
  mockStatus.isSuccess returns true

  val json = """
    {
       "results" : [
          {
             "elevation" : 8815.71582031250,
             "location" : {
                "lat" : 27.9880560,
                "lng" : 86.92527800000001
             },
             "resolution" : 152.7032318115234
          }
       ],
       "status" : "OK"
    }    
    """

  val body = HttpEntity(ContentType.`application/json`, json.getBytes())
  mockResponse.entity returns body

  val client = new ElevationClient{
    override def sendAndReceive = {
      (req:HttpRequest) => Promise.successful(mockResponse).future
    }
  }

  "A request to get an elevation" should{
    "return an elevation result" in {
      val fut = client.elavation
      val el = Await.result(fut, Duration(2, TimeUnit.SECONDS))
      val expected = GoogleApiResult("OK",List(Elevation(Location(27.988056,86.925278),8815.7158203125)))
      el mustEqual expected
    }
  }
}

ElevationClient所以我在这里的方法是首先在被调用中定义一个可覆盖的函数,sendAndReceive它只是委托给喷雾sendReceive函数。然后,在测试规范中,我重写了该sendAndReceive函数以返回一个函数,该函数返回一个完整的Future包装 a mock HttpResponse。这是做你想做的事情的一种方法。我希望这有帮助。

于 2013-05-16T14:27:25.640 回答
11

在这种情况下无需引入模拟,因为您可以使用现有 API 更轻松地构建 HttpResponse:

val mockResponse = HttpResponse(StatusCodes.OK, HttpEntity(ContentTypes.`application/json`, json.getBytes))

(很抱歉将此作为另一个答案发布,但没有足够的业力发表评论)

于 2013-11-11T09:04:02.280 回答