如何使用MockMVC测试使用org.apache.commons.fileupload的控制器?

yel*_*g99 0 file-upload spring-boot mockmvc

我的Controller使用“org.apache.commons.fileupload”实现了文件上传。看见:

 @PostMapping("/upload")
    public String upload2(HttpServletRequest request) throws Exception {

        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        boolean uploaded = false;

        while (iter.hasNext() && !uploaded) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                item.openStream().close();
            } else {
                String fieldName = item.getFieldName();
                if (!"file".equals(fieldName)) {
                    item.openStream().close();
                } else {

                    InputStream stream = item.openStream();
                    // dosomething here.
                    uploaded = true;
                }
            }
        }
            if (uploaded) {
                return "ok";
            } else {
                throw new BaseResponseException(HttpStatus.BAD_REQUEST, "400", "no file field or data file is empty.");
            }

        }
Run Code Online (Sandbox Code Playgroud)

我的 MockMvc 代码是

    public void upload() throws Exception {
        File file = new File("/Users/jianxiaowen/Documents/a.txt");
        MockMultipartFile multipartFile = new MockMultipartFile("file", new FileInputStream(file));
        HashMap<String, String> contentTypeParams = new HashMap<String, String>();
        contentTypeParams.put("boundary", "----WebKitFormBoundaryaDEFKSFMY18ehkjt");
        MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(baseUrl+"/upload")
                .content(multipartFile.getBytes())
                .contentType(mediaType)
                .header(Origin,OriginValue)
                .cookie(cookie))
                .andReturn();
        logResult(mvcResult);
    }
Run Code Online (Sandbox Code Playgroud)

我的控制器是对的,它在我的网络项目中成功了,但是我想使用 MvcMock 测试它,它有一些错误,请参阅: 有人可以帮助我吗?

"status":"400","msg":"no file field or data file is empty.","data":null
Run Code Online (Sandbox Code Playgroud)

我不知道为什么它说我的文件是空的。我的英语很差,如果有人能帮助我,非常感谢。

Mer*_*elm 5

MockMvc可用于使用Apache Commons Fileupload进行控制器的集成测试!

  1. 将其导入org.apache.httpcomponents:httpmime到您的pom.xmlgradle.properties

    <dependency>
       <groupId>org.apache.httpcomponents</groupId>
       <artifactId>httpmime</artifactId>
       <version>4.5.13</version>
    </dependency>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 更新用于MultipartEntityBuilder在客户端上构建多部分请求的代码,然后将实体序列化为字节,然后将其设置在请求内容中

    public void upload() throws Exception {
        File file = new File("/Users/jianxiaowen/Documents/a.txt");
    
        String boundary = "----WebKitFormBoundaryaDEFKSFMY18ehkjt";
    
        // create 'Content-Type' header for multipart along with boundary
        HashMap<String, String> contentTypeParams = new HashMap<String, String>();
        contentTypeParams.put("boundary", boundary); // set boundary in the header
        MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
    
        // create a multipart entity builder, and add parts (file/form data)
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        HttpEntity multipartEntity = MultipartEntityBuilder.create()
            .addPart("file", new FileBody(file, ContentType.create("text/plain"), file.getName())) // add file
            // .addTextBody("param1", "value1") // optionally add form data
            .setBoundary(boundary) // set boundary to be used
            .build();
        multipartEntity.writeTo(outputStream); // or getContent() to get content stream
        byte[] content = outputStream.toByteArray(); // serialize the content to bytes
    
        MvcResult mvcResult = mockMvc.perform(
            MockMvcRequestBuilders.post(baseUrl + "/upload")
                .contentType(mediaType)
                .content(content) // finally set the content
                .header(Origin,OriginValue)
                .cookie(cookie)
            ).andReturn();
        logResult(mvcResult);
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 最后,一个有用的答案。我将“FileBody”更改为“ByteArrayBody”,这样我就可以通过代码完成所有操作,而不依赖于文件系统中的任何内容。但这个答案正是我所需要的。谢谢你! (2认同)