spring-bootwebtestclient

Spring boot Web test client mock multipart file not working


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


Solution

  • 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();