Search code examples
javaannotationstestng

How to pass a variable from BeforeTest to Test annotation


I am trying to read data from excel in @BeforeTest method and trying to print same in @Test method in testNG. I have read the data in a sheet

@BeforeTest
    @Parameters({"filePath", "fileName", "sheetName"})
    public void readExcel(String filePath, String fileName, String sheetName) throws IOException, EncryptedDocumentException, InvalidFormatException{
        // set the file path
        File eFile = new File(filePath+"\\"+fileName);
        //print the file path
        System.out.println("File is at: "+eFile);

        FileInputStream inputstream = new FileInputStream(eFile);

        // Read and publish extension
        String extensionName = fileName.substring(fileName.indexOf("."));
        System.out.println("File type is: "+extensionName);

        //Read the file
        Workbook wb = new XSSFWorkbook(inputstream);

        //Read the sheet name
        Sheet wbSheet = wb.getSheet(sheetName);

    }

I would like to pass the wbSheet to @Test method to print and write data to excel. @Parameters is looking for constant defined in testng.xml. How to pass a variable like this..?


Solution

  • Why not use an instance variable?

    class YourClassTest {
    
      Sheet wbSheet;
    
      @BeforeTest public void readExcel(...) {
        wbSheet = wb.getSheet(sheetName);
      }
    
      @Test public void test() {
        //you can use wbSheet here
      }
    
    }