【发布时间】: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, () -> myService.doSomeRequest());? -
对不起 - 这是不正确的(在复制粘贴期间我搞砸了)。我已经更新了帖子,感谢您指出@Smile
标签: java unit-testing junit mockito sonarqube