WebClient throws WebClientRequestException on HTTP 200

72 Views Asked by At

When writing a unit test for WebClient using MockWebServer, the WebClientException is thrown showing HTTP 200. The code being tested works fine outside of the test but the unit test fails for some unknown reason.

The test which fails is -

   @Test
   void testMediaWebClientUpload() throws JsonProcessingException {
        FileUploadResponse response = new FileUploadResponse();
        response.setSuccess(true);
        mockWebServer.enqueue(new MockResponse()
            .setBody(objectMapper.writeValueAsString(response))
            .addHeader("ContentType", MediaType.MULTIPART_FORM_DATA));
        FileUploadResponse theResponse = client.upload("file","fileid");
        Assertions.assertTrue(response.isSuccess());
    }

when calling -

   public FileUploadResponse upload(String file, String fileId) throws Exception {

        try {
            Optional<FileUploadResponse> uploadResponse = webClient
                    .post()
                    .uri("/upload?file=" + file + "&fileid=" + fileId)
                    .contentType(MediaType.MULTIPART_FORM_DATA)
                    .retrieve()
                    .bodyToMono(FileUploadResponse.class)
                    .blockOptional();
            if (uploadResponse.isPresent()) {
                return uploadResponse.get();
            }
            return new FileUploadResponse();

        } catch (Exception ex) {
            Code statusCode = Code.INTERNAL;
            String message = "Internal server error";

Even though the request is HTTP 200 why is there an exception being thrown??

0

There are 0 best solutions below