【问题标题】:Spring MVC Image upload Integration test using Mockmvc and JSON failure使用 Mockmvc 和 JSON 失败的 Spring MVC 图片上传集成测试
【发布时间】:2015-01-19 16:26:39
【问题描述】:

我正在尝试使用我的测试类上传图片。我正在使用 JSON 使用 mockmvc 发送数据。我正在尝试将图像从我的 PC 添加到 JSON。我正在使用图像的链接将其添加到 JSON。 下面我给出了我的测试部分:

    @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.updateAccount(any(Account.class))).thenReturn(
                updateAccount);

        MockMultipartFile image = new MockMultipartFile("json", "", "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("image") 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);
    }
}

但是,出了点问题。我的控制台输出如下:

MockHttpServletRequest:
         HTTP Method = POST
         Request URI = /accounts/test/updateImage
          Parameters = {}
             Headers = {Content-Type=[multipart/form-data]}

             Handler:
                Type = web.rest.mvc.AccountController
              Method = public org.springframework.http.ResponseEntity<web.rest.resources.AccountResource> web.rest.mvc.AccountController.updateAccountImage(java.lang.String,org.springframework.web.multipart.MultipartFile)

               Async:
   Was async started = false
        Async result = null

  Resolved Exception:
                Type = org.springframework.web.bind.MissingServletRequestParameterException

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 400
       Error message = Required MultipartFile parameter 'image' is not present
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

我假设将图像添加到 JSON 时出现问题。谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: java json rest spring-mvc mockmvc


    【解决方案1】:

    MockMultipartFile 的初始参数是你的文件名,它必须与控制器方法中的参数名相匹配。你需要换成图片

    MockMultipartFile image = new MockMultipartFile("image", "", "application/json", "{\"image\": \"C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg\"}".getBytes());
    

    【讨论】:

    • 嗨,我改变了它,但我得到了一个不同的错误。错误是:“org.springframework.web.utill.NestedServletException:请求处理失败;嵌套异常是 java.lang.illigulArgument” 我尝试了不同的选择,也在很多地方搜索了解决方案,但失败了。你能告诉我这里有什么问题吗?
    【解决方案2】:

    这段代码还有另一个问题。控制器返回内部有图像的资源。导致处理失败。正确的代码如下:

    @测试部分

            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-01
      • 2016-06-13
      • 2017-06-03
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      • 2013-07-06
      • 2014-01-25
      • 2010-10-05
      相关资源
      最近更新 更多