Search code examples
javaspring-bootunit-testingspring-mvcmockito

Generating RestClientException error in mockito unit test


I am trying to validate a restclientexception error. My code is below and help would be appreciated. This is from my test class:`

`

@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());
}

This is from my injectMock class

`

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);
}

`


Solution

  • You can make your mock throw an exception when the exchange method is called:

    doThrow(new RestClientException())
                .when(restTemplate).exchange(any(), eq(HttpMethod.PATCH), any(HttpEntity.class), eq(String.class));
    

    And then verify the new exception thrown in the catchblock with assertThrows or assertThatCode(…).hasMessageContaining(…).