Reputation: 449
How to write a integration test when I'm uploading a image to the server. I've already written a test following this question and it's answer but mine is not working properly. I used JSON to send the image and expected status OK. But I'm getting:
org.springframework.web.utill.NestedServletException:Request Processing Failed;nested exception is java.lang.illigulArgument
or http status 400 or 415. I guess the meaning is same. Below I've given my test portion and controller class portion.
Test portion:
@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());
}
Controller portion:
@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);
}
}
If I write my controller this way It shows IllegalArgument in Junit trace but no problem in console and no mock print as well. So, I replace Controller with this:
@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);
}
}
Than I have this output in console:
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 = []
Now, I need to know how to solve this problem or should I take another approach and what is that.
Upvotes: 2
Views: 2761
Reputation: 1
I can test this using apache.commons.httpClient
library like shown below
@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();
//...
}
Upvotes: 0
Reputation: 449
The problem was because controller class is meant to receive multipart/form-data,but sent JSON data. There is another problem in this code. The controller returns the resource that having image inside. That causing processing failed. Right code is given below:
@test portion
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());
Controller Portion:
@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);
}
}
Upvotes: 1