1

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

Bully
  • 139
  • 1
  • 14

1 Answers1

2

You have not shared your controller, so I am 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.writeValueAsBytes(request));

        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;
}
rajadilipkolli
  • 3,475
  • 2
  • 26
  • 49
Emre Savcı
  • 3,034
  • 2
  • 16
  • 25
  • Thank you for your response but I realized that I have implementation in spring-integration-http. I don’t have Controller. Exception was invoked in UploadedMultipartFile class constructor. – Bully Aug 17 '18 at 15:52
  • Finally this example helped me to create an endpoint with a MultipartFile and a POJO parameter (it must be a `@RequestPart`!) and to successfully use it in a test (the combination of `.multipart` and serialising the POJO into JSON and wrap in a file). This issue was bothering me for a whole workday. Thank you! – Hawk Feb 24 '21 at 00:45