How can I simulate a POST request with a json body in SprayTest?

流过昼夜 提交于 2019-12-05 08:13:45
4lex1v

The trick is to set the correct Content-Type:

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

But it gets even simpler. If you have a spray-json dependency, then all you need to do is import:

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

the first import contains (un)marshaller which would convert your string into json request and you do not need to wrap it into HttpEntity with explicit media type.

the second import contains all Json readers/writers format for basic types. Now you can write just: Post("/api/authentication/signup", """{"email":"foo", "password":"foo:" }"""). But it's even cooler if you have some case class for this. For ex. you can define a case class Credentials, provide jsonFormat for this and use it in tests/project:

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

now in test:

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

spray automatically marshall it into Json request as application/json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!