问题描述
该文档的编写功能测试部分非常精简,并且缺少详细信息完全提交模拟表单值.我以某种方式(不记得如何/在何处)确定可以通过将Map
传递给FakeRequest
来提交基本表单值(模拟POST请求):
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.
推荐答案
我们的文件上传测试如下所示:
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))
其中"image"
是您希望在其中查找文件内容的HTML表单元素的名称.
where "image"
is the name of the HTML form element you expect to find the file contents in.
如果您使用BodyParsers.maxLength
限制上传的大小,则可以将formData
替换为Right(formData)
If you are using BodyParsers.maxLength
to limit the size of uploads, you can replace formData
with Right(formData)
这篇关于如何在Play框架(使用Scala的2.0版)中测试期望上传文件的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!