我试图验证一个restclientexception错误。我的代码如下,如果您能提供帮助,我将不胜感激。这是我的测试类:'
`
@Test
void test_update_customer_in_ath0_server_error(){
//given
ResponseEntity<String> responseEntity = new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
doReturn(responseEntity)
.when(restTemplate).exchange(any(), eq(HttpMethod.PATCH), any(HttpEntity.class), (Class<String>)any());
idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto);
//then
verify(restTemplate).exchange(any(), eq(HttpMethod.PATCH), argThat(this::verifyUpdatedCustomerBody), (Class<String>)any());
}
这是从我的injectMock类中得到的
`
try {
response = restTemplate.exchange(URI.create(idpFacadeUpdateUrl), HttpMethod.PATCH, entity, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
log.info("customer first name update success {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
}else {
log.error("Customer first name update failed in IDP for {} with status {}", customerUpdateRecordsDto.getFirstName(), response.getStatusCode());
}
} catch (RestClientException e) {
throw new RestClientException("Idp facade API error for user first name " + customerUpdateRecordsDto.getFirstName(), e);
}
`
2条答案
按热度按时间nbysray51#
如果您使用的是JUnit 5,请尝试将最后一行替换为如下内容:
在JUnit 4中,@Test注解提供了一个参数,用于指定测试的预期异常。
xmq68pz92#
当
exchange
方法被调用时,你可以让你的模拟抛出一个异常:然后使用
assertThrows
或assertThatCode(…).hasMessageContaining(…)
验证catchblock中引发的新异常。