'Writing Mockito Unit test for Optional with orElseThrow : Jacoco gives 0% code coverage
I am struggling to write a unit test for below logic having Optional and 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);
}
}
My Test
@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);
}
This case doesn't give any errors but Jacoco code coverage is 0%. Also, I am unable to understand how to include test case for NoSuchElementException as well.
Since the pom is huge, I am just adding the Mockito dependency here. It's 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>
Solution 1:[1]
You can add the statement below
when(employeeOperationService.getEmployeeById(any())).thenReturn(Optional.empty());
then it will throw a NoSuchElementException for your test case.
And I guess that some dependencies have compatible issue with Jacoco in your pom.xml, that's why you get 0% code coverage.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
