RESTful webservice与spring mvc的图片上传集成测试
Image uploading integration test of RESTful webservice with spring mvc
当我将图片上传到服务器时如何编写集成测试。我已经根据 this 问题编写了一个测试,它是答案,但我的无法正常工作。我使用 JSON 发送图像和预期状态 OK。但我得到:
org.springframework.web.utill.NestedServletException:Request
Processing Failed;nested exception is java.lang.illigulArgument
或http状态400或415。我猜意思是一样的。下面我给出了我的测试部分和控制器 class 部分。
测试部分:
@Test
public void updateAccountImage() throws Exception{
Account updateAccount = new Account();
updateAccount.setPassword("test");
updateAccount.setNamefirst("test");
updateAccount.setNamelast("test");
updateAccount.setEmail("test");
updateAccount.setCity("test");
updateAccount.setCountry("test");
updateAccount.setAbout("test");
BufferedImage img;
img = ImageIO.read(new File("C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg"));
WritableRaster raster = img .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] testImage = data.getData();
updateAccount.setImage(testImage);
when(service.updateAccountImage(any(Account.class))).thenReturn(
updateAccount);
MockMultipartFile image = new MockMultipartFile("image", "", "application/json", "{\"image\": \"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg\"}".getBytes());
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/accounts/test/updateImage")
.file(image))
.andDo(print())
.andExpect(status().isOk());
}
控制器部分:
@RequestMapping(value = "/accounts/{username}/updateImage", method = RequestMethod.POST)
public ResponseEntity<AccountResource> updateAccountImage(@PathVariable("username") String username,
@RequestParam(value="image", required = false) MultipartFile image) {
AccountResource resource =new AccountResource();
if (!image.isEmpty()) {
try {
resource.setImage(image.getBytes());
resource.setUsername(username);
} catch (IOException e) {
e.printStackTrace();
}
}
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
return new ResponseEntity<AccountResource>(res, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.EXPECTATION_FAILED);
}
}
如果我以这种方式编写我的控制器,它会在 Junit 跟踪中显示 IllegalArgument,但在控制台中没有问题,也没有模拟打印。所以,我用这个替换控制器:
@RequestMapping(value = "/accounts/{username}/updateImage", method = RequestMethod.POST)
public ResponseEntity<AccountResource> updateAccountImage(@PathVariable("username") String username,
@RequestBody AccountResource resource) {
resource.setUsername(username);
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
return new ResponseEntity<AccountResource>(res, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.EXPECTATION_FAILED);
}
}
比起我在控制台中的输出:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /accounts/test/updateImage
Parameters = {}
Headers = {Content-Type=[multipart/form-data;boundary=265001916915724]}
Handler:
Type = web.rest.mvc.AccountController
Method = public org.springframework.http.ResponseEntity<web.rest.resources.AccountResource> web.rest.mvc.AccountController.updateAccountImage(java.lang.String,web.rest.resources.AccountResource)
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 415
Error message = null
Headers = {Accept=[application/octet-stream, text/plain;charset=ISO-8859-1, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, application/json;charset=UTF-8, application/*+json;charset=UTF-8, */*]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
现在,我需要知道如何解决这个问题,或者我应该采用另一种方法,那是什么。
问题是因为控制器 class 本应接收 multipart/form-data,但发送了 JSON 数据。此代码中还有另一个问题。 controller returns 里面有图片的资源。导致处理失败。正确代码如下:
@测试部分
Account updateAccount = new Account();
updateAccount.setPassword("test");
updateAccount.setNamefirst("test");
updateAccount.setNamelast("test");
updateAccount.setEmail("test");
updateAccount.setCity("test");
updateAccount.setCountry("test");
updateAccount.setAbout("test");
BufferedImage img;
img = ImageIO.read(new File("C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg"));
WritableRaster raster = img .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] testImage = data.getData();
updateAccount.setImage(testImage);
FileInputStream fis = new FileInputStream("C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg");
MockMultipartFile image = new MockMultipartFile("image", fis);
HashMap<String, String> contentTypeParams = new HashMap<String, String>();
contentTypeParams.put("boundary", "265001916915724");
MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
when(service.updateAccountImage(any(Account.class))).thenReturn(
updateAccount);
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/accounts/test/updateImage")
.file(image)
.contentType(mediaType))
.andDo(print())
.andExpect(status().isOk());
控制器部分:
@RequestMapping(value = "/{username}/updateImage", method = RequestMethod.POST)
public @ResponseBody
ResponseEntity<AccountResource> updateAccountImage(@PathVariable("username") String username,
@RequestParam("image") final MultipartFile file)throws IOException {
AccountResource resource =new AccountResource();
resource.setImage(file.getBytes());
resource.setUsername(username);
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<AccountResource>(res,headers, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.NO_CONTENT);
}
}
我可以使用 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();
//...
}
当我将图片上传到服务器时如何编写集成测试。我已经根据 this 问题编写了一个测试,它是答案,但我的无法正常工作。我使用 JSON 发送图像和预期状态 OK。但我得到:
org.springframework.web.utill.NestedServletException:Request Processing Failed;nested exception is java.lang.illigulArgument
或http状态400或415。我猜意思是一样的。下面我给出了我的测试部分和控制器 class 部分。
测试部分:
@Test
public void updateAccountImage() throws Exception{
Account updateAccount = new Account();
updateAccount.setPassword("test");
updateAccount.setNamefirst("test");
updateAccount.setNamelast("test");
updateAccount.setEmail("test");
updateAccount.setCity("test");
updateAccount.setCountry("test");
updateAccount.setAbout("test");
BufferedImage img;
img = ImageIO.read(new File("C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg"));
WritableRaster raster = img .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] testImage = data.getData();
updateAccount.setImage(testImage);
when(service.updateAccountImage(any(Account.class))).thenReturn(
updateAccount);
MockMultipartFile image = new MockMultipartFile("image", "", "application/json", "{\"image\": \"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg\"}".getBytes());
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/accounts/test/updateImage")
.file(image))
.andDo(print())
.andExpect(status().isOk());
}
控制器部分:
@RequestMapping(value = "/accounts/{username}/updateImage", method = RequestMethod.POST)
public ResponseEntity<AccountResource> updateAccountImage(@PathVariable("username") String username,
@RequestParam(value="image", required = false) MultipartFile image) {
AccountResource resource =new AccountResource();
if (!image.isEmpty()) {
try {
resource.setImage(image.getBytes());
resource.setUsername(username);
} catch (IOException e) {
e.printStackTrace();
}
}
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
return new ResponseEntity<AccountResource>(res, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.EXPECTATION_FAILED);
}
}
如果我以这种方式编写我的控制器,它会在 Junit 跟踪中显示 IllegalArgument,但在控制台中没有问题,也没有模拟打印。所以,我用这个替换控制器:
@RequestMapping(value = "/accounts/{username}/updateImage", method = RequestMethod.POST)
public ResponseEntity<AccountResource> updateAccountImage(@PathVariable("username") String username,
@RequestBody AccountResource resource) {
resource.setUsername(username);
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
return new ResponseEntity<AccountResource>(res, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.EXPECTATION_FAILED);
}
}
比起我在控制台中的输出:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /accounts/test/updateImage
Parameters = {}
Headers = {Content-Type=[multipart/form-data;boundary=265001916915724]}
Handler:
Type = web.rest.mvc.AccountController
Method = public org.springframework.http.ResponseEntity<web.rest.resources.AccountResource> web.rest.mvc.AccountController.updateAccountImage(java.lang.String,web.rest.resources.AccountResource)
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 415
Error message = null
Headers = {Accept=[application/octet-stream, text/plain;charset=ISO-8859-1, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, application/json;charset=UTF-8, application/*+json;charset=UTF-8, */*]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
现在,我需要知道如何解决这个问题,或者我应该采用另一种方法,那是什么。
问题是因为控制器 class 本应接收 multipart/form-data,但发送了 JSON 数据。此代码中还有另一个问题。 controller returns 里面有图片的资源。导致处理失败。正确代码如下:
@测试部分
Account updateAccount = new Account();
updateAccount.setPassword("test");
updateAccount.setNamefirst("test");
updateAccount.setNamelast("test");
updateAccount.setEmail("test");
updateAccount.setCity("test");
updateAccount.setCountry("test");
updateAccount.setAbout("test");
BufferedImage img;
img = ImageIO.read(new File("C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg"));
WritableRaster raster = img .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] testImage = data.getData();
updateAccount.setImage(testImage);
FileInputStream fis = new FileInputStream("C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg");
MockMultipartFile image = new MockMultipartFile("image", fis);
HashMap<String, String> contentTypeParams = new HashMap<String, String>();
contentTypeParams.put("boundary", "265001916915724");
MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
when(service.updateAccountImage(any(Account.class))).thenReturn(
updateAccount);
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/accounts/test/updateImage")
.file(image)
.contentType(mediaType))
.andDo(print())
.andExpect(status().isOk());
控制器部分:
@RequestMapping(value = "/{username}/updateImage", method = RequestMethod.POST)
public @ResponseBody
ResponseEntity<AccountResource> updateAccountImage(@PathVariable("username") String username,
@RequestParam("image") final MultipartFile file)throws IOException {
AccountResource resource =new AccountResource();
resource.setImage(file.getBytes());
resource.setUsername(username);
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<AccountResource>(res,headers, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.NO_CONTENT);
}
}
我可以使用 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();
//...
}