如何在Play框架(使用Scala的2.0版)中测试期望上传文件的操作? [英] How to test actions that expect an uploaded file in Play Framework (version 2.0, using Scala)?

查看:86
本文介绍了如何在Play框架(使用Scala的2.0版)中测试期望上传文件的操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该文档的编写功能测试部分非常精简,并且缺少详细信息完全提交模拟表单值.我以某种方式(不记得如何/在何处)确定可以通过将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版)中测试期望上传文件的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆