简体   繁体   中英

Do I handle NulPointerException in my method or fix my unit test?

I have this method in my Java application:

@Override
public List<Client> getClients(String username) {
    ParameterizedTypeReference<List<Client>> tRef = new ParameterizedTypeReference<List<Client>>() {
    };
    HttpHeaders headers = createHeaders();
    headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
    HttpEntity<String> request = new HttpEntity<>(headers);
    ResponseEntity<List<Client>> response = restTemplate.exchange(aPIEndpoint + Constants.GET_CLIENTS,
            HttpMethod.GET, request, tRef, username);
    if (response.getStatusCode().is2xxSuccessful()) {
        return response.getBody();
    } else {
        return new ArrayList<>();
    }
}

I noticed in one of my unit tests that line if (response.getStatusCode().is2xxSuccessful()) { causes a NullPointerException . I'm wondering how I should deal with this. Should I handle this exception in my getClients() method or does my test need fixed in some way?

Just fixing your unit test won't help handling real error cases.

To me, your method would definitely benefit from a try / catch as it performs an external call which you can't predict.

Then, you could mock your API call and simulate various scenarios to make sure you handle all cases (success or failure) with unit tests.

You get NPE cause restTemplate.exchange(..) returns Null response.

RestTemplate can be mock object and you can return mock response.

using RestTemplate as mock. https://www.baeldung.com/spring-mock-rest-template

or use TestRestTempate . https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/web/client/TestRestTemplate.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM