Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
La prueba de integración con TestRestTemplate para la solicitud POST de varias partes devuelve 400

Sé que una pregunta similar ya ha estado aquí un par de veces, pero las siguientes soluciones sugeridas no resolvieron mi problema.

Tengo un controlador simple con el siguiente punto final:

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

Estoy tratando de escribir una prueba de integración usando Spring TestRestTemplate pero todos mis intentos terminan con 400 - Bad Request (no hay registros que aclaren qué salió mal en la consola).

El registro dentro del controlador no fue golpeado, por lo que falló antes de llegar allí.

¿Podría echar un vistazo a mi prueba y sugerir qué estoy haciendo mal?

 @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)); }
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Intenté lo siguiente:

 @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)); }

Como puede ver, utilicé org.springframework.core.io.ClassPathResource como objeto para el archivo y funcionó de maravilla.

espero que sea util

Ángel

about 4 years ago · Santiago Trujillo Report

0

FileSystemResource también podría usarse en caso de que desee usar java.nio.file.Path .

Paquete: org.springframework.core.io.FileSystemResource

Por ejemplo, podrías hacer esto:

 new FileSystemResource(Path.of("src", "test", "resources", "image.jpg"))

Ejemplo de código completo:

 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UploadFilesTest { private final TestRestTemplate template; @Autowired public UploadFilesTest(TestRestTemplate template) { this.template = template; } @Test public void uploadFileTest() { var multipart = new LinkedMultiValueMap<>(); multipart.add("file", file()); final ResponseEntity<String> post = template.postForEntity("/upload", new HttpEntity<>(multipart, headers()), String.class); assertEquals(HttpStatus.OK, post.getStatusCode()); } private HttpHeaders headers() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); return headers; } private FileSystemResource file() { return new FileSystemResource(Path.of("src", "test", "resources", "image.jpg")); } }

Controlador de descanso:

 @RestController public class UploadEndpoint { @PostMapping("/upload") public void uploadFile(@RequestParam("file") MultipartFile file) { System.out.println(file.getSize()); } }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!