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

If I have an endpoint that cancels json as follows:

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

How can I check this with the Spray specification:

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

This obviously does not work for several reasons. What will be the correct way?

+6
source share
1 answer

The trick is to set the right type of content:

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

But it gets even easier. If you have a dependency on the atomizer, then all you need to do is import:

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

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

the second import contains all Json read / write formats for the base types. Now you can simply write: Post("/api/authentication/signup", """{"email":"foo", "password":"foo:" }""") . But it's even cooler if you have a class for this occasion. E.g. you can define 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 the test:

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

spray automatically sorts it into Json request as application/json

+11
source

Source: https://habr.com/ru/post/954559/


All Articles