Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.59k stars 593 forks source link

MockClient mapError failed to map object #373

Closed Dutzen closed 3 years ago

Dutzen commented 3 years ago

If i mock the client (MockClient) and return an ErrorObject. The mappedErrorObject is null due to Nullpointer Exception in the mappError method.

The Nullpointer is produced by the config in the try catch block (see below) (config = null) so the objectMapper can't be called on the object and the method returns null.

BaseResponse.java
 @Override
    public <E> E mapError(Class<? extends E> errorClass) {
        if (!isSuccess()) {
            String errorBody = getErrorBody();
            if(String.class.equals(errorClass)){
                return (E) errorBody;
            }
            try {
                return config.getObjectMapper().readValue(errorBody, errorClass);
            } catch (RuntimeException e) {
                setParsingException(errorBody, e);
            }
        }
        return null;
    }

The mappedError is still null even if i return a ResponseBody.

To Reproduce

  1. Mock the client and expect:
    MockClient mock = MockClient.register();
    mock.expect(HttpMethod.GET, url).thenReturn(errorResponseDTO).withStatus(INTERNAL_SERVER_ERROR); 

Expected behavior The errorResponseDTO is returned when calling Unirest.get(url).asObject(ItemDTO.class).mapError(ErrorResponseDTO.class) but its null.

Environmental Data:

ryber commented 3 years ago

Complete in 3.11.02