How do I make a Junit test to test a method that returns XSSFWorkbook?

422 Views Asked by At

I have a method like this


public XSSFWorkbook createWorkbook(List<Object> Object){

        String[] headers = new String[]{"Header1","Header2"......};
    
        XSSFWorkbook workbook = new XSSFWorkbook();

        Sheet sheet = workbook.createSheet("Object");
        sheet.setColumnWidth(0, 6000);
        sheet.setColumnWidth(1, 4000);

        Row header = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            //logic for adding headers in the first row
            header.createCell(i).setCellValue(headers[i]);
        }
        
        for(int x=0; x<Object.size();x++){

            Row data = sheet.createRow(x+1);

            for(int y=0;y<headers.length;y++){
            //logic for adding cell data

            }
        }

       return workbook;
    }

I have another method that does the actual processing of the workbook file to an xlsx file.

I just need to make a unit test for this specific method

How do I create a mock workbook or something that I can assert to the workbook I create in my original method? Something like this?

    @Test
    void test_createWorkbook() throws Exception{

        XSSFWorkbook mockWorkbook = mock(XSSFWorkbook.class);

        List<Object> data = new ArrayList<Object>();
        //Populate data list logic here.

        XSSFWorkbook actualWorkbook = myservice.createWorkbook(data);
        Assertions.assertEquals(mockWorkbook,actualWorkbook);
    }

Problem with this is that the mockWorkbook is just filled with null data.

1

There are 1 best solutions below

1
SnazzY808 On

I decided to just make assertions to the specific contents of the workbook instead of actually making another mock workbook. Like this

@Test
    void test_createWorkbook() throws Exception{

List<Object> data = new ArrayList<Object>();
//Populate data list logic here.

XSSFWorkbook actualWorkbook = myservice.createWorkbook(data);
Assertions.assertEquals("Header1",actualWorkbookgetSheetAt(0).getRow(0).getCell(0).getStringCellValue());
Assertions.assertEquals("Header2",actualWorkbookgetSheetAt(0).getRow(0).getCell(1).getStringCellValue());
//And so on 
        }