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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With