How to PUT multipart/form-data using Spring MockMvc?

前端 未结 3 2076
無奈伤痛
無奈伤痛 2021-01-17 07:33

I have a controller\'s method with a PUT method, which receives multipart/form-data:

   @RequestMapping(value = \"/putIn\", method = RequestMeth         


        
3条回答
  •  迷失自我
    2021-01-17 08:14

    You can pass both foo and file

    Try rewrite you controller like:

    @RequestMapping(value = "/putIn", method = RequestMethod.PUT)
    public Foo updateFoo(
        HttpServletRequest request,
        @RequestPart Foo foo,
        @RequestPart MultipartFile file) {
        ...
    }
    

    And test looks like:

        MockMultipartFile file = new MockMultipartFile("file", "dummy.csv",
                "text/plain", "Some dataset...".getBytes());
        // application/json if you pass json as string
        MockMultipartFile file2 = new MockMultipartFile("foo", "foo.txt",
                "application/json", "Foo data".getBytes());
    
        MockMultipartHttpServletRequestBuilder builder =
                MockMvcRequestBuilders.multipart("/test1/datasets/set1");
        builder.with(new RequestPostProcessor() {
            @Override
            public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
                request.setMethod("PUT");
                return request;
            }
        });
        mvc.perform(builder
                .file(file)
                .file(file2))
                .andExpect(status().ok());
    

提交回复
热议问题