I am getting Null pointer while testing the below code
public static List<String> getColumnList(Row row) {
List<String> columnList = new ArrayList<>();
**for(Cell cell : row){**
if(StringUtils.isEmpty(cell.getStringCellValue())){
break;
}else{
columnList.add(cell.getStringCellValue());
}
}
return columnList;
}
The test code is given below
Workbook mockWorkbook = mock(Workbook.class);
Sheet mockSheet = mock(Sheet.class);
Row mockRow = mock(Row.class);
Cell mockCell1 = mock(Cell.class);
Cell mockCell2 = mock(Cell.class);
Cell mockCell3 = mock(Cell.class);
Cell mockCell4 = mock(Cell.class);
when(mockWorkbook.createSheet("m_digi_svce_func_asset_cat")).thenReturn(mockSheet);
when(mockWorkbook.getNumberOfSheets()).thenReturn(1);
when(mockWorkbook.getSheetAt(0)).thenReturn(mockSheet);
when(mockWorkbook.isSheetHidden(0)).thenReturn(false);
when(mockSheet.getSheetName()).thenReturn("m_digi_svce_func_asset_cat");
when(mockWorkbook.getSheet("m_digi_svce_func_asset_cat")).thenReturn(mockSheet);
when(mockSheet.createRow(0)).thenReturn(mockRow);
when(mockRow.createCell(0)).thenReturn(mockCell1);
when(mockRow.createCell(1)).thenReturn(mockCell2);
when(mockRow.createCell(2)).thenReturn(mockCell3);
when(mockRow.createCell(3)).thenReturn(mockCell4);
when(mockRow.getCell(0)).thenReturn(mockCell1);
when(mockCell1.getStringCellValue()).thenReturn("test1");
when(mockRow.getCell(1)).thenReturn(mockCell2);
when(mockCell2.getStringCellValue()).thenReturn("test2");
when(mockRow.getCell(2)).thenReturn(mockCell3);
when(mockCell3.getStringCellValue()).thenReturn("test3");
when(mockRow.getCell(3)).thenReturn(mockCell4);
when(mockCell4.getStringCellValue()).thenReturn("test4");
assertNotNull(mockRow.getCell(0).getStringCellValue());
assertNotNull(getColumnList(mockRow));
The code is failing at for each loop of Row in getColumnList saying Row is null.
Any help/pointer would be highly appreciated.
As suggested by Lesiak, I added the below code and it is working fine now.
Iterator<Cell> cellIterator = mock(Iterator.class);
when(mockRow.iterator()).thenReturn(cellIterator);
when(cellIterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(cellIterator.next()).thenReturn(mockCell1).thenReturn(mockCell2).thenReturn(mockCell3).thenReturn(mockCell4);
when(mockRow.getCell(0)).thenReturn(mockCell1);
when(mockCell1.getStringCellValue()).thenReturn("test1");
when(mockRow.getCell(1)).thenReturn(mockCell2);
when(mockCell2.getStringCellValue()).thenReturn("test2");
when(mockRow.getCell(2)).thenReturn(mockCell3);
when(mockCell3.getStringCellValue()).thenReturn("test3");
when(mockRow.getCell(3)).thenReturn(mockCell4);
when(mockCell4.getStringCellValue()).thenReturn("test4");
assertNotNull(mockRow.getCell(0).getStringCellValue());