我正在努力为具有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依赖项。
<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>
1条答案
按热度按时间qnzebej01#
您可以添加以下语句
那么它将为您的测试用例抛出一个
NoSuchElementException
。我猜一些依赖项与
pom.xml
中的Jacoco存在兼容问题,这就是为什么代码覆盖率为0%的原因。https://github.com/mockito/mockito/issues/1717