Как написать интеграционный тест, когда я загружаю изображение на сервер. Я уже написал тест после этого вопрос и ответ на него, но мой не работает должным образом. Я использовал JSON для отправки изображения и ожидаемого статуса OK. Но я получаю:
org.springframework.web.util.NestedServletException: Ошибка обработки запроса; вложенным исключением является java.lang.illigulArgument
или статус http 400 или 415. Думаю, смысл тот же. Ниже я привел свою тестовую часть и часть класса контроллера.
Тестовая часть:
@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);
}
}
Если я напишу свой контроллер таким образом, он покажет IllegalArgument в трассировке Junit, но не будет проблем в консоли и не будет фиктивной печати. Итак, я заменяю Controller на это:
@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 = []
Теперь мне нужно знать, как решить эту проблему или мне следует использовать другой подход и что это такое.