Интеграционный тест загрузки изображений веб-сервиса RESTful с Spring MVC

Как написать интеграционный тест, когда я загружаю изображение на сервер. Я уже написал тест после этого вопрос и ответ на него, но мой не работает должным образом. Я использовал 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 = []

Теперь мне нужно знать, как решить эту проблему или мне следует использовать другой подход и что это такое.


person Mahin    schedule 21.01.2015    source источник


Ответы (2)


Проблема заключалась в том, что класс контроллера предназначен для получения данных multipart/form, но отправляет данные JSON. В этом коде есть еще одна проблема. Контроллер возвращает ресурс, внутри которого находится изображение. Это привело к сбою обработки. Правильный код приведен ниже:

@тестовая часть

        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);
    }
}
person Mahin    schedule 25.01.2015

Я могу проверить это, используя библиотеку 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();
        //...
}
person Sourabh Yadav    schedule 29.08.2017