【问题标题】:Line is not covered according to test coverage, despite successfully using verify and asserts尽管成功使用了验证和断言,但根据测试覆盖率未覆盖行
【发布时间】:2021-01-30 20:25:37
【问题描述】:

我的目标是让 Sonar 检测到 MyService 类中抛出的错误(通过注释指出)实际上已包含在测试中。然而,Sonar 表示并非如此。尽管成功验证了 logAndThrowException 方法被调用,Sonar 仍然说这条线没有被测试覆盖。

MyService 类:

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 类:

public class MyExceptionHandler {
    public void logAndThrowException(String msg) throws MyCustomException {
        // do some logs
        throw new MyCustomException();
    }
}

测试代码:

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

【问题讨论】:

  • 为什么你的测试用例中有Mockito.doThrow(MyCustomException.class, () -&gt; myService.doSomeRequest());
  • 对不起 - 这是不正确的(在复制粘贴期间我搞砸了)。我已经更新了帖子,感谢您指出@Smile

标签: java unit-testing junit mockito sonarqube


【解决方案1】:

我相信我以前见过这个。问题是它没有“完成”执行该行,因为在执行该行时引发了异常。

【讨论】:

  • 感谢大卫的评论!很有趣,所以我认为这是无法在覆盖范围内修复的问题,应该保持原样?
猜你喜欢
  • 2015-12-14
  • 2018-10-18
  • 2023-03-27
  • 1970-01-01
  • 2015-02-08
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多