2013-09-25 45 views
6

如果我有一個JSON解組這樣的端點:如何在SprayTest中使用json主體模擬POST請求?

(path("signup")& post) { 
    entity(as[Credentials]) { credentials => 
    … 

我如何可以測試用噴霧測試規範:

"The Authentication service" should { 

"create a new account if none exists" in { 
    Post("/api/authentication/signup", """{"email":"foo", "password":"foo:" }""") ~> authenticationRoute ~> check { 
    handled === true 
    } 
} 
} 

這顯然不會有幾個原因的工作。什麼是正確的方法?

回答

11

關鍵是要設置正確的Content-Type:

Post("/api/authentication/signup", 
    HttpBody(MediaTypes.`application/json`, 
      """{"email":"foo", "password":"foo" }""") 
) 

但它變得更簡單。如果你有一個噴霧JSON的依賴,那麼所有你需要做的是進口:

import spray.httpx.SprayJsonSupport._ 
import spray.json.DefaultJsonProtocol._ 

首次進口含有(UN)編組這將您的字符串轉換成JSON請求,你不需要把它包裝成HttpEntity與明確的媒體類型。

第二個導入包含基本類型的所有Json讀寫器格式。現在你可以只寫:Post("/api/authentication/signup", """{"email":"foo", "password":"foo:" }""")。但是如果你有這樣的案例課,它會更酷。例如。您可以定義一個case class Credentials,爲此提供jsonFormat並在測試中使用它/項目:

case class Creds(email: String, password: String) 
object Creds extends DefaultJsonProtocol { 
    implicit val credsJson = jsonFormat2(Creds.apply) 
} 
現在

測試:

Post("/api/authentication/signup", Creds("foo", "pass")) 

噴霧自動馬歇爾成JSON請求爲application/json

+8

我相信這不再適用於最新版本。取而代之的是:'''Post(「/ api/authentication/signup」,HttpEntity(MediaTypes.'application/json',「」「{」email「:」foo「,」password「:」foo「}」 「))))''' –

+1

@GregaKešpret它可以完美的與任何版本兼容。目前在噴1.3.1 with akka 2.3.3 – 4lex1v

+1

@AlexIv HttpBody所在的對象在哪裏? –