maloney
maloney

Reputation: 1653

Spray MultipartFormData Spec

I have a spray endpoint which accepts a MultipartFormData like this:

trait ApiRouting extends Routing with ResultService with FormDataUnmarshallers {
  override def route: Route =
   path("test") {
     post {
       entity(as[MultipartFormData]) { formData =>
         complete(handleRequest(formData))
       }
     }
   }
}

This works fine when I post via postman. However, I am trying to write a spec that tests this endpoint and get this error:

java.lang.ClassCastException: spray.http.HttpEntity$Empty$ cannot be cast to spray.http.HttpEntity$NonEmpty

This is what I have:

trait Context extends Scope with ApiRouting {}

  "check post request" should {

    "return response data for post request" in new Context {

      val file = new File("test")
      val httpEntity = HttpEntity(MediaTypes.`multipart/form-data`, HttpData(file)).asInstanceOf[HttpEntity.NonEmpty]
      val formFile = FormFile("file", httpEntity)
      val mfd = MultipartFormData(Seq(BodyPart(formFile, "file")))

      Post("/test", mfd) ~> route ~> check {
        status must_== StatusCodes.OK
        contentType must_== `multipart/form-data`    
      }
    }
  }

Any ideas on how to test a spray multipart form data?

Upvotes: 0

Views: 543

Answers (1)

Artsiom Miklushou
Artsiom Miklushou

Reputation: 754

It's happening because your are passing zero-length file into HttpData. Try to refer to a real file.

Also, you can pass your File directly into BodyPart. It will looks like:

Post(Uri("/test"),
      MultipartFormData(
        Seq(BodyPart(file, "file", ContentType(MediaTypes.`application/xml`)))
      )
    )

Upvotes: 2

Related Questions