Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing MultipartFile with WebtestClient

I am writing unit tests for my controller class. I am using spring webflux. Hence I am writing tests with WebTestClient. Here is my controller method

@PutMapping("/updatedocument/{documentType}")
public ResponseEntity<String> updateDocument(@PathVariable String documentType,
                                             @RequestParam("file") MultipartFile file) {
     ...................
}

This code is working when I call from Postman or any rest client. I am having difficulty in writing unit test. I am getting

"Required MultipartFile parameter 'file' is not present"

Error . Here is my test method.

@Test
void updateDocument() throws IOException {

    .............
    MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
    multipartBodyBuilder.part("file", new ClassPathResource("somefile"))
            .contentType(MediaType.MULTIPART_FORM_DATA)

    webTestClient.put()
            .uri("/customer/updatedocument/ID")
            .body(BodyInserters.fromMultipartData(multipartBodyBuilder.build()))
            .exchange()
            .expectStatus().isOk();
}

Any suggestion is much appreciated. Please NOTE. I am using WebTestClient and not MovkMvc

like image 735
pvpkiran Avatar asked Jun 28 '26 14:06

pvpkiran


1 Answers

I was able to solve this issue. The main culprit is my controller method and not the test method.

Had to change couple of things in controller method. When using spring web flux(reactive) we should use

1.@RequestPart instead of @RequestParam
2. FilePart instead of MultipartFile

So the controller method will look like this.

@PutMapping("/updatedocument/{documentType}")
public ResponseEntity<String> updateDocument(@PathVariable DocumentType documentType,
                                             @RequestPart("file") FilePart filePart) {
   .....................
}

You can convert FilePart to File object.

like image 88
pvpkiran Avatar answered Jun 30 '26 05:06

pvpkiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!