【发布时间】:2013-12-21 18:55:12
【问题描述】:
我创建了一个使用 javax.ws.rs 效果很好的照片上传器。这是它的签名和基本要点:
@POST
@Path("/upload/photo")
@Consumes("multipart/form-data")
@Produces("application/json")
public String uploadPhoto(InputStream stream){
try {
int read = 0;
FileOutputStream fos = new FileOutputStream(file);
CountingOutputStream out = new CountingOutputStream(fos);
byte[] bytes = new byte[MAX_UPLOAD_SIZE];
while ((read = stream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
// TODO throw!
e.printStackTrace();
}
//...
}
我可以像这样使用 apache.commons.httpClient 库对此进行测试:
@Test
public void testUpload() {
int statusCode = 0;
String methodResult = null;
String endpoint = SERVICE_HOST + "/upload/photo";
PostMethod post = new PostMethod(endpoint);
File file = new File("/home/me/Desktop/someFolder/image.jpg");
FileRequestEntity entity = new FileRequestEntity(file, "multipart/form-data");
post.setRequestEntity(entity);
try {
httpClient.executeMethod(post);
methodResult = post.getResponseBodyAsString();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
statusCode = post.getStatusCode();
post.releaseConnection();
//...
}
这很好用!问题是应用程序的其余部分是使用 Spring MVC 编写的。当我使用 Spring Mock MVC 测试框架时,程序只是挂起(显示在这个下面的代码 sn-p 中)。这是上传者的SpringMVC代码:
@ResponseBody
@RequestMapping( produces="application/json",
consumes="multipart/form-data",
method=RequestMethod.POST,
value="/photo")
public String uploadPhoto(@RequestPart("file") MultipartFile multipartFile){
try {
int read = 0;
FileOutputStream fos = new FileOutputStream(file);
CountingOutputStream out = new CountingOutputStream(fos);
byte[] bytes = new byte[MAX_UPLOAD_SIZE];
while ((read = multipartFile.getInputStream().read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
// TODO throw!
e.printStackTrace();
}
//...
}
下面是我使用 Spring Mock MVC 实现的测试。我认为问题与使用 fileUpload(...) 有关。有没有办法使用普通的 post(..) 来测试,就像我可以使用 apache 一样?我更喜欢使用 InputStream 作为参数,避免使用 MultipartFile。
@Test
public void testUpload() throws Exception {
String endpoint = BASE_URL + "/upload/photo";
FileInputStream fis = new FileInputStream("/home/me/Desktop/someFolder/image.jpg");
MockMultipartFile multipartFile = new MockMultipartFile("file", fis);
mockMvc.perform(fileUpload(endpoint)
.file(multipartFile)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk());
}
理想情况下,我想使用 Spring MVC 和 Spring Mock MVC 框架,但我提供的代码只是挂在 while 语句上。就在 Spring 测试中使用 fileUpload 方法而言,我所做的是否正确?任何建议表示赞赏。
【问题讨论】:
-
冗长的代码示例...某处出了点问题...您的实际问题是什么? -1
标签: java rest spring-mvc