6

The Writing functional tests portion of the documentation is pretty skimpy and lacks details on submitting mock form values completely. I somehow (can't remember how/where) determined you can submit basic form values (mocking a POST request) by passing a Map to FakeRequest like so:

val Some(result) = routeAndCall(FakeRequest(POST, "/path/to/test", FakeHeaders(),
                                Map("postedVariable" -> Seq("and a value"))))

However, that doesn't seem to allow for the case of an "uploaded" file.

Alex Varju
  • 2,922
  • 3
  • 24
  • 22
Chris W.
  • 1,680
  • 16
  • 35

1 Answers1

12

Our file upload tests look something like this:

val tempFile = TemporaryFile(new java.io.File("/tmp/the.file"))
val part = FilePart[TemporaryFile](key = "image", filename = "the.file", contentType = Some("image/jpeg"), ref = tempFile)
val formData = MultipartFormData(dataParts = Map(), files = Seq(part), badParts = Seq(), missingFileParts = Seq())
val result = routeAndCall(FakeRequest(POST, "/path/to/test", FakeHeaders(), formData))

where "image" is the name of the HTML form element you expect to find the file contents in.

If you are using BodyParsers.maxLength to limit the size of uploads, you can replace formData with Right(formData)

Alex Varju
  • 2,922
  • 3
  • 24
  • 22
  • That's what I needed! Except one problem: When constructing the `FakeRequest`, I had to remove the `Right` wrapper that you had around `formData`; thus, the last line should be: `val result = routeAndCall(FakeRequest(POST, "/path/to/test", FakeHeaders(), formData))` – Chris W. Nov 21 '12 at 20:09
  • And I also want to note that the `key` parameter for the `FilePart` should be the name that your HTML form's file input uses. – Chris W. Nov 21 '12 at 20:11
  • Sorry, the `Right` wrapper was because we use `BodyParsers.maxLength` to limit the size of uploads. I forgot to strip that out when building my example. – Alex Varju Nov 21 '12 at 21:21