我是在方法中处理NulpoInterException还是修复了单元测试?
我的Java应用程序中有此方法:
@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<>();
}
}
我在我的单元测试之一中注意到该行 if(wissy.getStatusCode()。is2xxsuccessful()){
导致 nullpointerexception
。我想知道我该如何处理。我应该在getClients()方法中处理此例外,还是我的测试需要以某种方式解决?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅修复单元测试不会有助于处理实际错误案例。
对我来说,您的方法肯定会从尝试 /捕获中受益,因为它执行了无法预测的外部呼叫。
然后,您可以模拟API调用并模拟各种方案,以确保通过单位测试处理所有情况(成功或失败)。
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.
您会得到NPE原因
RESTTEMPLATE.EXCHANGE(..)
返回null响应。RESTTEMPLATE可以是模拟对象,您可以返回模拟响应。
将RESTTEMPLAPE用作模拟。 https://wwwww.baeldung.com/spring-mock-mock-mock-rest-template
或使用
testRestTempate
。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