[英]Writing Mockito Unit test for Optional with orElseThrow : Jacoco gives 0% code coverage
我正在努力为具有 Optional 和 orElseThrow 的以下逻辑编写单元测试
class EmployeeHandler {
public Employee getEmployeeById(Long id) {
return employeeService.getEmployeeById(id)
.map(apiMapper::toEmployeeOperationDTO)
.orElseThrow(NoSuchElementException::new);
}
}
public interface ApiMapper {
EmployeeOperationDTO toEmployeeOperationDTO(EmployeeOperationn entity);
}
public class ApiMapperImpl implements ApiMapper {
public EmployeeOperationDTO toEmployeeOperationDTO(EmployeeOperationn entity) {
// EmployeeOperationDTO Object creation logic
}
}
class EmployeeOperationService {
EmployeeOperationRepository employeeOperationRepo;
public Optional<EmployeeOperation> getEmployeeById(Long id) {
employeeOperationRepo.findById(id);
}
}
我的测试
@Mock
private EmployeeOperationRepository employeeOperationRepo;
@Mock
private EmployeeOperationService employeeOperationService;
@MockApiMapper apiMapper;
@InjectMock
private EmployeeHandler employeeHandler;
@beforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void getEmployeeById() {
//getDto will create a sample dto object
EmployeeOperationDTO dto = getDto();
//getEoObject will create EmployeeOperation object
EmployeeOperation eo = getEoObject();
Long id = 1L;
when(employeeOperationRepo.findById(id)).thenReturn(Optional.of(eo));
doReturn(Optional.of(eo)).when(employeeOperationService).getEmployeeById(any());
when(apiMapper.toEmployeeOperationDTO(eo )).thenReturn(dto);
final EmployeeOperationDTO empDto = employeeHandler.getEmployeeById(id);
Assertions.assertNotNull(empDto);
}
这种情况不会给出任何错误,但 Jacoco 代码覆盖率为 0%。 另外,我也无法理解如何包含 NoSuchElementException 的测试用例。
由于 pom 很大,我只是在这里添加 Mockito 依赖项。 这是 Mockito 4.0.0
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito.inline</artifactId>
<scope>test<test>
<dependency>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven.inline</artifactId>
<executions>
<execution>
<id>check</id>
<goals>
<goal>check</goal>
</goals>
<Configuration>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVERAGERATIO</value>
<minimum>0</minimum>
</limit>
</limit>
</rule>
</rules>
</execution>
</executions>
您可以在下面添加语句
when(employeeOperationService.getEmployeeById(any())).thenReturn(Optional.empty());
然后它将为您的测试用例抛出一个NoSuchElementException
。
而且我猜某些依赖项与 pom.xml 中的pom.xml
存在兼容问题,这就是为什么代码覆盖率为 0% 的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.