如何解决具有restTemplate.delete和Exxception的Mockito测试服务方法
我有以下服务方法:
@Override
public void deleteGreetingById(Integer greetingId) {
try {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:9123/greetings/" + greetingId);
restTemplate.delete(builder.toUriString());
}catch(HttpClientErrorException ex){
if(ex.getStatusCode().equals(HttpStatus.NOT_FOUND))
throw new GreetingNotFoundException("Greeting with id: " + greetingId + " not found.");
}
}
因此,如您所见,我正在调用第二个服务,该服务管理所有问候语以按ID删除特定的问候语。因此,此方法没有太多逻辑。我要测试的是,如果rest调用引发状态代码为404的HttpClientException,则会引发预期的GreetingNotFoundExcpetion。
我厌倦了用模仿者定义测试。由于restTemtplate.delete“返回” void,因此我必须根据文档使用“ doThrow”方法。 所以我这样定义测试:
@Test
public void deleteGreetingByIdInvalidId(){
UriComponentsBuilder builder=UriComponentsBuilder.fromHttpUrl("http://localhost:9123/greetings/1");
doThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)).when(restTemplate).delete(builder.toUriString());
greetingsService.deleteGreetingById(1);
}
我考虑过要这样做。首先定义,其余的模板执行会导致HttpClientErrorExceptin带有404,然后定义为抛出GreetingNotFoundException。我试图将GreetingNotFoundException部分定义为
doThrow(new GreetingNotFoundException("Greeting with id: 1 not found.")).when(greetingsService).deleteGreetingById(1);
问题是,greetingService是通过@InjectMocks注入的。所以我得到了错误,greeingservice不是Mock。 我只想执行真正的方法(例如使用spy时),但是我认为使用@InjectMocks时已经完成了。
我刚刚从嘲笑和atm开始,我对处理这两个void方法感到困惑。预先感谢
解决方法
发布此问题后,我立即找到了解决方案。在这里为任何遇到相同问题的人提供帮助。
@Test
public void deleteGreetingByIdInvalidId(){
UriComponentsBuilder builder=UriComponentsBuilder.fromHttpUrl("http://localhost:9123/greetings/1");
doThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)).when(restTemplate).delete(builder.toUriString());
Exception exception = assertThrows(GreetingNotFoundException.class,() ->{greetingsService.deleteGreetingById(1);});
assertTrue(exception.getMessage().contains("Greeting with id: 1 not found."));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。