使用 orElseThrow 编写可选的 Mockito 单元测试:Jacoco 的代码覆盖率为 0%

use*_*941 2 java junit unit-testing mockito jacoco

我正在努力为具有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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试

@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);
}
Run Code Online (Sandbox Code Playgroud)

此案例没有给出任何错误,但 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>
Run Code Online (Sandbox Code Playgroud)

Kai*_*ang 5

您可以添加下面的语句

when(employeeOperationService.getEmployeeById(any())).thenReturn(Optional.empty());
Run Code Online (Sandbox Code Playgroud)

NoSuchElementException然后它会为您的测试用例抛出一个。

我猜想某些依赖项与您的 Jacoco 存在兼容问题pom.xml,这就是您获得 0% 代码覆盖率的原因。

https://github.com/mockito/mockito/issues/1717