【发布时间】:2017-08-09 17:26:17
【问题描述】:
我在我的代码中使用了restTemplate.postForEntity()。
在围绕它测试类时,我使用 Mockito 来模拟 RestTemplate。
Mockito.when(restTemplate.postForEntity(.....)).thenReturn(response)
响应在哪里:
ResponseEntity<String> response = new ResponseEntity(HttpStatus.UNAUTHORIZED);
现在,当我运行此测试时,postForEntity 返回我刚刚显示的模拟响应。但是,在实际执行中,RestTemplate 在从远程接收到401 时会抛出RestClientException。
这是因为RestTemplate 中的doExecute() 检查错误并在出现4XX 和5XX 错误时抛出此异常。
我当然可以重写模拟规则:
Mockito.when(restTemplate.postForEntity(.....)).thenThrow(new RestClientException(..)).
但是在阅读测试时,这不是很直观:我希望它本身响应 401 或 500。
我应该怎么做才能做到这一点?
【问题讨论】:
-
如果你模拟
RestTemplate,那么要走的路是thenThrow(new RestClientException(..)(注意你也可以使用真正的RestTemplate和mock the Http server)
标签: java spring mockito resttemplate