2

将图像上传到服务器时如何编写集成测试。我已经在这个 问题之后编写了一个测试并且它的答案,但我的工作不正常。我使用 JSON 发送图像和预期状态 OK。但我得到:

org.springframework.web.utill.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);
    }
}

如果我以这种方式编写控制器,它将在 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 = []

现在,我需要知道如何解决这个问题,或者我应该采取另一种方法,那是什么。

4

2 回答 2

1

问题是因为控制器类旨在接收多部分/表单数据,但发送的是 JSON 数据。这段代码还有另一个问题。控制器返回内部有图像的资源。导致处理失败。正确的代码如下:

@test 部分

        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);
    }
}
于 2015-01-25T16:30:03.540 回答
0

我可以使用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();
        //...
}
于 2017-08-29T08:16:22.887 回答