如果我有一个端点解组json像这样:
- (path("signup")& post) {
- entity(as[Credentials]) { credentials =>
- …
如何使用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
- }
- }
- }
由于几个原因,这显然不起作用.什么是正确的方法?
解决方法
诀窍是设置正确的内容类型:
- Post("/api/authentication/signup",HttpBody(MediaTypes.`application/json`,"password":"foo" }""")
- )
但它变得更加简单.如果你有一个spray-json依赖项,那么你需要做的就是导入:
- import spray.httpx.SprayJsonSupport._
- import spray.json.DefaultJsonProtocol._
第一个导入包含(un)marshaller,它将你的字符串转换为json请求,你不需要用显式媒体类型将它包装到HttpEntity中.
第二个导入包含基本类型的所有Json读取器/写入器格式.现在你可以写:Post(“/ api / authentication / signup”,“”“{”email“:”foo“,”password“:”foo:“}”“”).但如果你有一些案例类,那就更酷了.对于前者您可以定义一个案例类Credentials,为此提供jsonFormat并在tests / project中使用它:
- 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