Spring MVC Test - multipart POST json originalFile

2019-08-16 16:36发布

问题:

I use spring-boot 2.0.3.RELEASE with junit5. I have just tried to test multipart request with mockMvc.

MockMultipartFile file = new MockMultipartFile("file", "contract.pdf", MediaType.APPLICATION_PDF_VALUE, "<<pdf data>>".getBytes(StandardCharsets.UTF_8));
MockMultipartFile metadata = new MockMultipartFile("metadata", "", MediaType.APPLICATION_JSON_VALUE, objectMapper.writeValueAsString(metadata).getBytes(StandardCharsets.UTF_8));
this.mockMvc.perform(multipart("/documents")
        .file(file)
        .file(metadata))
        .andExpect(status().isNoContent());

But it is not working with part metadata (json).

I always get exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: originalFilename is required.

What is wrong?

EDIT:

My implementation is in spring integration dsl. I think that exception is invoked in org.springframework.integration.http.multipart.UploadedMultipartFile. How can I test multipart request with mockMvc?

@Bean
public IntegrationFlow multipartForm() {
    return IntegrationFlows.from(Http.inboundChannelAdapter("/documents")
            .statusCodeExpression(HttpStatus.NO_CONTENT.toString())
            .requestMapping(m -> m
                    .methods(HttpMethod.POST)
                    .consumes(MediaType.MULTIPART_FORM_DATA_VALUE)
            ))
            .handle(new MultipartReceiver())
            .get();
}

My demo project is in github https://github.com/bulalak/demo-spring-integration-http

回答1:

You have not shared your controller so I writing here an example from mine.

Here is a test with MultipartFile in spring boot :

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
    @Autowired
    MockMvc mockMvc;

    @MockBean
    UserService userService;

    @Test
    public void test() throws Exception {
        UserCreateRequest request = new UserCreateRequest();
        request.setName("test");
        request.setBirthDate(new Date());
        request.setGender("male");

        MockMultipartFile file =
                new MockMultipartFile(
                        "file",
                        "contract.pdf",
                        MediaType.APPLICATION_PDF_VALUE,
                        "<<pdf data>>".getBytes(StandardCharsets.UTF_8));

        ObjectMapper objectMapper = new ObjectMapper();

        MockMultipartFile metadata =
                new MockMultipartFile(
                        "request",
                        "request",
                        MediaType.APPLICATION_JSON_VALUE,
                        objectMapper.writeValueAsString(request).getBytes(StandardCharsets.UTF_8));

        mockMvc.perform(
                multipart("/users/")
                        .file(file)
                        .file(metadata)
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());

    }
}

User controller :

@RestController
@RequestMapping("/users")
public class UserController {

    UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping({"/", ""})
    public ResponseEntity<User> post(@RequestPart("request") UserCreateRequest request, @RequestPart("file") MultipartFile file) throws IOException {

        String photoPath = UUID.randomUUID() + file.getOriginalFilename().replaceAll(" ", "").trim();

        // other logic

        request.setPhone(photoPath);

        return ResponseEntity.ok(userService.create(request));
    }
}

UserCreateRequest :

@Data // from lombok
public class UserCreateRequest {
    private String name;
    private String phone;
    private String surname;
    private String gender;
    private Date birthDate;
    private String bio;
    private String photo;
}