Home > other >  Generating RestClientException error in mockito unit test
Generating RestClientException error in mockito unit test

Time:11-13

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

`

CodePudding user response:

If you are working with JUnit5, try replacing the last line with something like this:

assertThrows(RestClientException.class, () -> idpFacadeClient.updateCustomerFirstNameInIdp(updateRecordsDto));

In JUnit4 the @Test annotation provides a parameter to specify an expected exception for the test.

CodePudding user response:

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(…).

  • Related