Integration test with TestRestTemplate for Multipart POST request returns 400

Smajl :

I know that similar question has been here already couple of times but following suggested fixes did not solve my problem.

I have a simple controller with the following endpoint:

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> singleFileUpload(@RequestParam("file") MultipartFile file) {
    log.debug("Upload controller - POST: {}", file.getOriginalFilename());

    // do something
}

I am trying to write an integration test for it using Spring TestRestTemplate but all of my attemps end with 400 - Bad Request (no logs clarifying what went wrong in console).

The log inside the controller did not get hit so it failed before getting there.

Could you please take a look on my test and suggest what am I doing wrong?

@Test
public void testUpload() {
    // simulate multipartfile upload
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("image.jpg").getFile());

    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.add("file", file);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(parameters, headers);

    ResponseEntity<String> response = testRestTemplate.exchange(UPLOAD, HttpMethod.POST, entity, String.class, "");

    // Expect Ok
    assertThat(response.getStatusCode(), is(HttpStatus.OK));
}
Angelo Immediata :

I tried the following:

@Test
public void testUpload() {
    LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.add("file", new org.springframework.core.io.ClassPathResource("image.jpg"));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<LinkedMultiValueMap<String, Object>>(parameters, headers);

    ResponseEntity<String> response = testRestTemplate.exchange(UPLOAD, HttpMethod.POST, entity, String.class, "");

    // Expect Ok
    assertThat(response.getStatusCode(), is(HttpStatus.OK));
}

As you can see I used the org.springframework.core.io.ClassPathResource as object for the file and ti worked like a charm

I hope it's useful

Angelo

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=460685&siteId=1