如何在SprayTest中使用json主体模拟POST请求?

iwe*_*ein 6 spray spray-test

如果我有一个端点解组json像这样:

(path("signup")& post) {
    entity(as[Credentials]) { credentials =>
    …
Run Code Online (Sandbox Code Playgroud)

如何使用Spray测试规范测试:

"The Authentication service" should {

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

由于几个原因,这显然不起作用.什么是正确的方法?

4le*_*x1v 12

诀窍是设置正确的内容类型:

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

但它变得更加简单.如果你有一个spray-json依赖项,那么你需要做的就是导入:

import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
Run Code Online (Sandbox Code Playgroud)

第一个导入包含(un)marshaller,它会将您的字符串转换为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)
}
Run Code Online (Sandbox Code Playgroud)

现在在测试中:

Post("/api/authentication/signup", Creds("foo", "pass"))
Run Code Online (Sandbox Code Playgroud)

喷雾自动将其编入Json请求中作为 application/json

  • 我相信这不再适用于最新版本.相反,这样做:```Post("/ api/authentication/signup",HttpEntity(MediaTypes .application/json`,"""{"email":"foo","password":"foo"}" "")))``` (8认同)