I have this method and implementation is done. However, when I look at Jacoco report, it says that the else {} and catch() part is not being covered by Unit Test Code Coverage.
public class SomeService {
public List<Something> getAll() throws SomeCustomException {
List<Something> listOfSomething = new ArrayList<>();
try (Data data = DataUtil.get(Constants.SOME_TABLE_NAME)){
ResultSet resultSet = data.retrieveAll();
if(resultSet != null && !resultSet.isEmpty()){
Something something;
for (ResultSetRow row : resultSet){
something = new Something();
something.setX(row.get("someColumnX"));
//...
listOfSomething.add(something);
}
}else{
throw new SomeCustomException("ResultSet is null");
}
}catch (ExceptionOne | ExceptionTwo e){
throw new SomeCustomException(e.getMessage(), e);
}
return listOfSomething;
}
}
So I tried to create a Unit Test method to attempt to cover the else(){} part. However, I think what I'm doing is not correct or has no effect to the someServiceMock
Basically, I want the resultSet to be empty so that it goes to the else {} part and cover the test on else {} branch. Problem is, I'm not sure how to set it because it's inside the getAll() method
@Test
void getAllReturnsEmpty() {
SomeService someServiceMock = mock(SomeService.class);
ResultSet resultSetMock = mock(ResultSet.class);
when(!resultSetMock.isEmpty).thenReturn(false);
assertThat(someServiceMock.getAll().isEmpty()).isTrue();
}
Is there a way to achieve what I want? I want to hava 99% Java code coverage
Thank you
Like people stated in the comments, you're mocking the wrong things. You can mock static things (like "DataUtil#get"), but since this doesn't go to the core of the question, let's say we have
To get your coverage, you can then
All four of these need to be in separate test cases (with the same verification).