gpt4 book ai didi

java - 在 Play 2.0 FakeRequest 中测试 MultipartFormData

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:30 25 4
gpt4 key购买 nike

我正在尝试为 Play 2 Controller 创建一个功能测试,它将多部分表单数据作为输入。目前 FakeRequest 中没有支持多部分表单 POST 的方法。还有什么其他方法可以测试这个 Controller ?

Map<String, Object> map = new HashMap<String, Object>();
map.put("param1", "test-1");
map.put("param2", "test-2");
map.put("file", file)
Result result = routeAndCall(fakeRequest(POST, "/register").withFormUrlEncodedBody(map));// NO SUCH METHOD

编辑:这是我为测试多部分所做的解决方法。

    HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:3333/blobupload");

FileBody imageFile = new FileBody(new File("test/resources/test-1.jpg"));
StringBody guid1 = null;
StringBody guid2 = null;
try {
guid1 = new StringBody("GUID-1");

} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("key1", imageFile);
reqEntity.addPart("key2", guid1);

httppost.setEntity(reqEntity);

HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

最佳答案

你应该使用 callAction 来使用 withFormUrlEncodedBody

@Test
public void testMyAction() {
running(fakeApplication(), new Runnable() {
public void run() {
Map<String,String> data = new HashMap<String, Object>();
data.put("param1", "test-1");
data.put("param2", "test-2");
data.put("file", file);

Result result = callAction(
controllers.whatever.action(),
fakeRequest().withFormUrlEncodedBody(data)
)
...
}
}
}

我只将 Scala api 用于 Play Framework 2,但我认为您不能使用 withFormUrlEncodedBody 测试多部分表单。

在 Scala 中你可以这样做:

import play.api.libs.Files._
import play.api.mvc.MultipartFormData._

class MyTestSpec extends Specification {

"mytest should bla bla bla" in {
running(FakeApplication(aditionalConfiguration = inMemoryDatabase())) {
val data = new MultipartFormData(Map(
("param1" -> Seq("test-1")),
("param2" -> Seq("test-2"))
), List(
FilePart("payload", "message", Some("Content-Type: multipart/form-data"), play.api.libs.Files.TemporaryFile(new java.io.File("/tmp/pepe.txt")))
), List(), List())

val Some(result) = routeAndCall(FakeRequest(POST, "/route/action", FakeHeaders(), data))
...
}
}
}

我猜你可以将它翻译成 Java,抱歉,我不知道如何用 Java 编写代码。

P.D:对不起我的英语我还在学习

关于java - 在 Play 2.0 FakeRequest 中测试 MultipartFormData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10890381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com