I am writing a unit test for a servlet that uses an excel file as input stream using the poi library
org.apache.poi
This is the servlet:
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); RequestParameter xlsxFile = request.getRequestParameter("xlsxfile"); final InputStream inputStream = xlsxFile.getInputStream(); try (inputStream) { Workbook workbook = new XSSFWorkbook(inputStream); // Use XSSFWorkbook for xlsx files json = extractData(workbook); } catch (IOException e) { throw new RuntimeException("Could not parse XLSX file", e); }}
This is the Unit Test:
@Testvoid testExcelFileImport() throws IOException { InputStream inputStream = MyServlet.class.getResourceAsStream("/component/tools/excel-import/import/excel-data.xlsx"); byte[] bytes = IOUtils.toByteArray(inputStream); context.request().addRequestParameter("xlsxfile", bytes, "xlsxfile", "excel-file.xlsx"); MockSlingHttpServletRequest request = context.request(); MockSlingHttpServletResponse response = context.response(); underTest.doPost(request, response); assertEquals("Success: Excel correctly imported as JSON", response.toString())}
Updating Media
Workbook workbook = new XSSFWorkbook(inputStream)