我在我的代码中使用了restTemplate.postForEntity()
。 当测试它周围的类时,我使用Mockito来模拟RestTemplate。如何用Client或Server错误模拟RestTemplate?
Mockito.when(restTemplate.postForEntity(.....)).thenReturn(response)
,其中反应是:
ResponseEntity<String> response = new ResponseEntity(HttpStatus.UNAUTHORIZED);
现在,当我运行这个测试,postForEntity
返回模拟响应我刚才给。但是,在实际执行中,RestTemplate在从远程接收到401
时会抛出RestClientException
。
这是因为doExecute()
在RestTemplate
检查错误并在4XX和5XX错误的情况下引发此异常。
我当然可以改写模拟规则:
Mockito.when(restTemplate.postForEntity(.....)).thenThrow(new RestClientException(..))
。
但是在阅读测试时,这不是很直观:我希望它响应401或500本身。
我该怎么做才能做到这一点?
要走的路是'thenThrow(新RestClientException(..)'如果你嘲笑'RestTemplate'(注意你也可以使用真正的RestTemplate和[模拟Http服务器](https://www.google.com/search?q=mock+http+server)) – 2017-08-09 17:30:09