1 | initial version |
There are several steps to creating a JUnit 5 Testing Service that can access and read an Excel file:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
TestWatcher
class. The TestWatcher
class provides hooks for executing code before and after each test method. public class ExcelReaderTest extends TestWatcher {
// code goes here
}
Workbook
instance variable that will hold the Excel file contents.public class ExcelReaderTest extends TestWatcher {
private Workbook workbook;
}
starting(ExtensionContext)
method of the TestWatcher
class to load the Excel file and save its contents to the workbook
variable. You'll need to specify the path to the Excel file in your project, using a java.io.File
object.@Override
protected void starting(ExtensionContext context) throws IOException {
File excelFile = new File("path/to/excel/file.xlsx");
FileInputStream inputStream = new FileInputStream(excelFile);
workbook = new XSSFWorkbook(inputStream);
}
workbook
variable to read data from the Excel file. You can use the Workbook
API to access sheets, rows, and cells in the Excel file, and read their values.@Test
void testReadCellValue() {
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
assertEquals("Hello, world!", cell.getStringCellValue());
}
finished(ExtensionContext)
method to close any resources that were opened in the starting(ExtensionContext)
method.@Override
protected void finished(ExtensionContext context) {
try {
if (workbook != null) {
workbook.close();
}
} catch (IOException e) {
// handle the exception
}
}
That's it! You should now have a JUnit 5 Testing Service that can access and read an Excel file.