java - Spring MVC 图片上传使用 Mockmvc 和 JSON 集成测试失败

标签 java json rest spring-mvc mockmvc

我试图使用我的测试类上传图像。我正在使用 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());

    }

这是 Controller 部分:

@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 时出现问题。谁能告诉我如何解决这个问题?

最佳答案

MockMultipartFile 的初始参数是文件的名称,它必须与 Controller 方法内的参数名称匹配。您需要更改为图像

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

关于java - Spring MVC 图片上传使用 Mockmvc 和 JSON 集成测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28029203/

相关文章:

Django 测试 - 发送包含整数的数组数组

json - 在 Angular 2 中使用 JSON 正文发出 POST 请求

java - 使用模拟对象进行 junit 测试 : stub inner function calls

python - 将带有标题的 HTML 表转换为 Json - Python

java - 如何为应用程序上的用户制作一次性 "I agree" Activity 屏幕?

c# - 如何反序列化 JArray?

c# - JSON 序列化程序写入过多 ']'

node.js - 推送通知 RESTful WebApp Angular2/NodeJS

java - Clojure 中是否有适用于 Java 函数的应用函数?

java - 如果在线程上调用 java wait(),该方法也会在 run() 方法终止时退出