Mathias Arens
Mathias Arens

Reputation: 317

Unable to upload file with WebTestClient in SpringBootTest

I am not able to upload a file with a WebTestClient in a SpringBootApplicationTest

This is my test:

@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationTest {

    @Autowired
    private WebTestClient webTestClient;
    
    @Test
    void saveDocumentSuccessfully() throws IOException {
        webTestClient.post().uri("/upload")
         .contentType(MediaType.MULTIPART_FORM_DATA)
         .body(BodyInserters.fromMultipartData(createMultipartBodyBuilder().build()))
         .exchange()
         .expectStatus().is2xxSuccessful();
    }
    
    private @NotNull MultipartBodyBuilder createMultipartBodyBuilder() throws IOException {
        final MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
        multipartBodyBuilder.part("document", 
            Files.readAllBytes(Path.of("src/test/resources/thumb_oct22_02.jpg")), 
            MediaType.IMAGE_JPEG);
        return multipartBodyBuilder;
    }

}

This is my UploadController:

@RestController
public class UploadController {

    @PostMapping(value ="/upload")
    public void upload(@RequestPart final MultipartFile document) {
        System.out.println("File uploaded: " + document.getOriginalFilename());
    }

}

I do get the error

{"type":"about:blank","title":"Bad Request","status":400,"detail":"Required part 'document' is not present.","instance":"/upload"} 

back

If I run the application locally, I can upload a file with a external restclient. What do I do wrong?

Upvotes: 0

Views: 67

Answers (1)

Peng
Peng

Reputation: 1314

multipartBodyBuilder.part("document", new FileSystemResource("src/test/resources/thumb_oct22_02.jpg"))
                            .contentType(MediaType.IMAGE_JPEG);

FileSystemResource : This class wraps file as Resource ,which is what Spring expect multipart file uploads , The file content and metadata(like filename and contentType) are correctly handled

Upvotes: 1

Related Questions