2013-05-16 12 views
15

alay nasılBasit sprey müşterim var spreyle istemci yanıtı

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() 
} 

Tam kod here bulunabilir.

Success ve Failure durumlarındaki mantığı sınamak için sunucunun yanıtıyla uğraşmak istiyorum. Bulduğum tek ilgili bilgi here idi, ancak ben sendReceive yöntemini alay etmek için kek desenini kullanamamıştım.

Herhangi bir öneri veya örnek çok takdir edilecektir.

cevap

19

Test özellikleri için specs2'yi ve alay için mockito'yu kullanarak alay etmenin bir yolunun bir örneği. Birincisi, Main nesne alay için bir sınıf kurulum içine refactored:

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() 
    } 
} 

Daha sonra, test spec:

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 
    } 
    } 
} 

Yani benim yaklaşım burada ilk sendAndReceive denilen ElevationClient bir geçersiz kılınabilir işlevini tanımlamak olduğunu sadece sprey sendReceive işlevine delege. Daha sonra, test özelliklerinde, bir sahte HttpResponse kaydırma tamamlanmış bir işlev döndüren bir işlevi döndürmek için sendAndReceive işlevini geçersiz kılar. Bu yapmak istediğin şeyi yapmak için bir yaklaşım. Umarım bu yardımcı olur.

+0

Tam olarak aradığım şey. Teşekkürler! – Eleni

+2

Sadece 'Promise.successful (mockResponse) .future' yerine 'Future.successful (mockResponse)' kullanabiliriz. Ben de 'addAndReceive' değerini geçersiz kılmak yerine 'ElevationClient' argümanını yapmayı tercih ederim. Sonra 'sendAndReceive' için bir Function' [HttpRequest, Future [HttpResponse]] 'a alay etirdik. – Alden

11

sadece bir HttpResponse çok daha kolay kullanarak mevcut API oluşturmak gibi bu durumda alay tanıtmak için gerek yoktur: Başka bir cevap olarak bu yazabilmek için

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

(Maalesef yok Yorum yapmak için yeterli karma)

İlgili konular