My goal is for Sonar to detect that the error thrown in the MyService class (pointed through the comment) is actually covered in the test. However, Sonar says it is not. Despite successfully verifying that the logAndThrowException method is called, Sonar still says this line is not covered in the test.
MyService class:
public class MyService {
@Autowired
RestTemplate restTemplate;
@Autowired
MyExceptionHandler myExceptionHandler;
public ResponseEntity doSomeRequest() {
try {
ResponseEntity<String> response = restTemplate.exchange(requestEntity, String.class);
if (responseEntity.getStatusCode() == HttpStates.OK) {
return response;
}
myExceptionHandler.logAndThrowException("error"); // Sonar says this line is not covered in tests
} catch (RestClientException e) {
// Handle it
}
}
}
MyExceptionHandler class:
public class MyExceptionHandler {
public void logAndThrowException(String msg) throws MyCustomException {
// do some logs
throw new MyCustomException();
}
}
Test code:
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@Mock
private RestTemplate restTemplate
@Mock
MyExceptionHandler myExceptionHandler;
@Mock
ResponseEntity responseEntity;
@InjectMocks
MyService myService = new MyService();
@Test
public void testFailedRequest() {
when(restTemplate.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(responseEntity);
when(responseEntity.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
Mockito.doThrow(MyCustomException.class).when(myExceptionHandler).logAndThrowException(ArgumentMatchers.anyString());
assertThrows(MyCustomException.class, () -> myService.doSomeRequest());
Mockito.verify(myExceptionHandler, Mockito.times(1)).logAndThrowException(ArgumentMatchers.anyString());
}
}