Line is not covered according to test coverage, despite successfully using verify and asserts

Viewed 420

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

I believe I've seen this before. The issue is that it doesn't "finish" executing that line, because an exception is thrown while executing that line.

Related