Java restfulwebservice与springmvc的图像上传集成测试

Java restfulwebservice与springmvc的图像上传集成测试,java,rest,spring-mvc,integration-testing,mockmvc,Java,Rest,Spring Mvc,Integration Testing,Mockmvc,如何在将映像上载到服务器时编写集成测试。我已经写了一个测试下面的问题和它的答案,但我的工作不正常。我使用JSON发送图像和预期状态OK。但我得到了: org.springframework.web.utill.NestedServletException:请求 处理失败;嵌套的异常是java.lang.illigulArgument 或http状态400或415。我想意思是一样的。下面我给出了我的测试部分和控制器类部分 试验部分: @Test public void updateAccountI

如何在将映像上载到服务器时编写集成测试。我已经写了一个测试下面的问题和它的答案,但我的工作不正常。我使用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);
    }
}
@RequestMapping(value=“/accounts/{username}/updateImage”,method=RequestMethod.POST)
public ResponseEntity updateAccountImage(@PathVariable(“用户名”)字符串用户名,
@RequestParam(value=“image”,required=false)多部分文件映像){
AccountResource=新的AccountResource();
如果(!image.isEmpty()){
试一试{
resource.setImage(image.getBytes());
resource.setUsername(用户名);
}捕获(IOE异常){
e、 printStackTrace();
}
}
Account=accountService.updateAccountImage(resource.toAccount());
如果(帐户!=null){
AccountResource res=新AccountResourceAsm().toResource(帐户);
返回新的响应状态(res,HttpStatus.OK);
}否则{
返回新的响应属性(HttpStatus.EXPECTATION\u失败);
}
}
若我以这种方式编写控制器,它在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);
        }
    }
@RequestMapping(value=“/accounts/{username}/updateImage”,method=RequestMethod.POST)
public ResponseEntity updateAccountImage(@PathVariable(“用户名”)字符串用户名,
@请求主体帐户(资源){
resource.setUsername(用户名);
Account=accountService.updateAccountImage(resource.toAccount());
如果(帐户!=null){
AccountResource res=新AccountResourceAsm().toResource(帐户);
返回新的响应状态(res,HttpStatus.OK);
}否则{
返回新的响应属性(HttpStatus.EXPECTATION\u失败);
}
}
然后在控制台中有以下输出:

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 = []
MockHttpServletRequest:
HTTP方法=POST
请求URI=/accounts/test/updateImage
参数={}
标题={Content Type=[multipart/form data;boundary=265001916915724]}
处理程序:
类型=web.rest.mvc.AccountController
Method=public org.springframework.http.ResponseEntity web.rest.mvc.AccountController.updateAccountImage(java.lang.String,web.rest.resources.AccountResource)
异步:
Was async start=false
异步结果=空
已解决的异常:
Type=org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
视图名称=空
视图=空
模型=空
FlashMap:
MockHttpServletResponse:
状态=415
错误消息=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,*/*]}
内容类型=空
正文=
转发的URL=null
重定向的URL=null
Cookies=[]

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

问题是因为控制器类要接收多部分/表单数据,但要发送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());
Account updateAccount=new Account();
updateAccount.setPassword(“测试”);
updateAccount.setNamefirst(“测试”);
updateAccount.setNamelast(“测试”);
updateAccount.setEmail(“测试”);
updateAccount.setCity(“测试”);
updateAccount.setCountry(“测试”);
updateAccount.setAbout(“测试”);
缓冲图像img;
img=ImageIO.read(新文件(“C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg”);
WritableRaster raster=img.getRaster();
DataBufferByte数据=(DataBufferByte)光栅。getDataBuffer();
字节[]testImage=data.getData();
updateAccount.setImage(testImage);
FileInputStream fis=新的FileInputStream(“C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg”);
MockMultipartFile image=新的MockMultipartFile(“image”,fis);
HashMap contentTypeParams=新HashMap();
contentTypeParams.put(“边界”,“265001916915724”);
MediaType MediaType=新的MediaType(“多部分”、“表单数据”、contentTypeParams);
当(service.updateAccountImage(any(Account.class))。然后返回(
更新计数);
mockMvc.perform(
MockMvcRequestBuilders.fileUpload(“/accounts/test/updateImage”)
.file(图像)
.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);
    }
}
@RequestMapping(value=“/{username}/updateImage”,method=RequestMethod.POST)
公共@ResponseBody
ResponseEntity updateAccountImage(@PathVariable(“用户名”)字符串用户名,
@RequestParam(“图像”)最终多部分文件)引发IOException{
AccountResource=新的AccountResource();
resource.setImage(file.getBytes());
resource.setUsername(用户名);
雅库
@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();
        //...
}