Spring boot Web test client mock multipart file not working

1.8k views Asked by At
MockMultipartFile file = new MockMultipartFile("files",
                             "Test.txt", 
                             "text/plain", 
  this.getClass().getResourceAsStream("/Test.txt"));
        
webTestClient.post()
                .uri("/foo").header("test", "1")
                .header("test1", "1")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(BodyInserters.fromMultipartData("files", file))
            .exchange()
                .expectStatus().isOk();

Getting exception :

org.springframework.core.codec.CodecException: 
Type definition error: [simple type, class java.io.ByteArrayInputStream]; 
nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 
No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer
 (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
 (through reference chain: org.springframework.mock.web.MockMultipartFile["inputStream"])

Where as it is working fine with my postman. Please find the attached screenshot of postmanenter image description here

1

There are 1 answers

0
Prashant Thorat On BEST ANSWER
webTestClient.post()
                .uri("/foo").header("test", "1")
                .header("test1", "1")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(BodyInserters.fromMultipartData("files", this.getClass().getResource("/Test.txt")))
            .exchange()
                .expectStatus().isOk();