2015-08-25 32 views
3

我正在使用spray-client在e2e測試中向我的服務器生成http請求。我也使用specs2來測試服務器所需的響應。一切正常。 我已經構建了一些自定義specs2匹配器來簡化我的測試代碼。我的測試是這樣的:解組仿真泛型類型

val response = get(<server_endpoint_url>) 

response must beSuccessfulWith(content = expected_data) 

我有一個特點是在某種程度上簡化噴霧的使用在測試本身:

trait SprayTestClientSupport { 
    implicit val system = ActorSystem() 
    import system.dispatcher // execution context for futures 

    val pipeline: HttpRequest => Future[HttpResponse] = sendReceive 

    def get(url: String): Future[HttpResponse] = pipeline(Get(url)) 
} 

我也有一個特點,我確定我在使用自定義的匹配測試:

trait SprayTestClientSupport extends ShouldMatchers with SprayJsonSupport with DefaultJsonProtocol { 
    def beSuccessfulWith(content: Seq[Int]): Matcher[Future[HttpResponse]] = 
     beSuccessful and haveBodyWith(content) 

    def haveBodyWith(content: Seq[Int]): Matcher[Future[HttpResponse]] = 
     containTheSameElementsAs(content) ^^ { f: Future[HttpResponse] => 
     Await.result(f, await).entity.as[Seq[Int]].right.get 
     } 

    def beSuccessful: Matcher[Future[HttpResponse]] = 
     ===(StatusCode.int2StatusCode(200)) ^^ { f: Future[HttpResponse] => 
     Await.result(f, await).status 
     } 
} 

當我嘗試使匹配器更通用並支持任何Scala類型時,我的問題就開始了。我定義是這樣的:

def haveBodyWith[T: TypeTag](content: T): Matcher[Future[HttpResponse]] = 
    ===(content) ^^ { f: Future[HttpResponse] => 
    Await.result(f, await).entity.as[T].right.get 
} 

但後來我收到以下錯誤信息:

Error:(49, 86) could not find implicit value for parameter unmarshaller: spray.httpx.unmarshalling.Unmarshaller[T] 
===(content) ^^ { (f: Future[HttpResponse]) => { Await.result(f, await).entity.as[T].right.get } } 

有什麼簡單的我失蹤?

謝謝!

P.S. 
I use the following spray versions: 
spray-client_2.10 -> 1.3.3 
spray-can_2.10 -> 1.3.3 
spray-http_2.10 -> 1.3.3 
spray-httpx_2.10 -> 1.3.3 
spray-util_2.10 -> 1.3.3 
spray-json_2.10 -> 1.3.2 

回答

3

您需要將約束添加到您的T參數

def haveBodyWith[T: TypeTag : Unmarshaller](content: T): Matcher[Future[HttpResponse]] = 
    ===(content) ^^ { f: Future[HttpResponse] => 
    Await.result(f, await).entity.as[T].right.get 
} 
+0

一樣方便的是,和它的作品。謝謝! – anatolyr