6

次のように json を非整列化するエンドポイントがある場合:

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

それは明らかにいくつかの理由で機能しません。正しい方法は何ですか?

4

1 に答える 1

12

トリックは、正しい Content-Type を設定することです:

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

しかし、それはさらに単純になります。Spray-json 依存関係がある場合は、インポートするだけです。

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

HttpEntity最初のインポートには、文字列を json リクエストに変換する (un)marshaller が含まれており、明示的なメディア タイプでラップする必要はありません。

2 番目のインポートには、基本型のすべての 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

于 2013-09-25T13:09:08.493 に答える