0

I have the following situation. I would like to use mockito to test the try/catch block of my service function : GettingMyDataService. Any hint or tips please ?

//in the controller
@GetMapping("/data")
public ResponseEntity gettingMyDataController(@RequestParam(request = true) String dataId) {

  gettingMyDataService.getDataFunction(dataId);
}
@Service
// my first service
public class GettingMyDataService {

  @AutoWired
   MyCustomRestClient myCustomRestClient

  
  public void getDataFunction(String dataId) {
    MyDataEntityDTO myDataEntityDTO; 
    
    try {
      myDataEntityDTO = myCustomRestClient.callReadExternalSIService(dataId);

    } catch (HttpStatusException e) {
      if (e.getStatusCode().value() == 404) {
        throw new CustomException1(".......");
      } 
      else {
        throw new CustomException2(".....");
      }
    }
}
@Service
// 2nd service for RestTemplate
public class myCustomRestClient {
  
  public callReadExternalSIService(String dataId) {
    String uri = "http:// ..."

    HttpEntity<MyDataEntityDTO> res = RestTemplate.getForEntity(uri + dataId, MyDataEntityDTO.class);
  
    return res.getBody(); 
  }
}

M. Dao
  • 42
  • 1
  • 7

1 Answers1

1

An example to let your custom REST client throw an exception:

MyCustomRestClient mock = Mockito.mock(MyCustomRestClient.class);
HttpStatusCodeException exception = new HttpClientErrorException(HttpStatus.NOT_FOUND);
Mockito.doThrow(exception).when(mock).callReadExternalSIService("data");
slauth
  • 2,667
  • 1
  • 10
  • 18