我在我的代碼中使用了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