Search code examples
javajsonrestspring-mvcmockmvc

Spring MVC Image upload Integration test using Mockmvc and JSON failure


I was trying to upload an image using my test class. I am using JSON to send the data using mockmvc.I am trying to add a Image from my PC to JSON. I am using link of the image to add it to the JSON. Below I've given my 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.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());

    }

And here is the controller portion:

@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);
    }
}

But, something went wrong. My console output is below:

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 = []

I am assuming there is a problem with adding my image to JSON. Could anyone tell me how to solve this?


Solution

  • The initial parameter of the MockMultipartFile is the name of your file, and it must match the name of the argument inside the controller method. You need to change to image

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