如何把一个方法放在我@beforeTest

How to put a method i @beforeTest

这里是selenium/java菜鸟。 :) 试图了解有关测试注释的所有内容以及如何在所有 classes.

中使用方法(是否称为该方法)

我在下面有这个 class,我在每个 @Test 中调用了一个方法,但我想在 @BforeTest 中尽可能多地添加一些内容,或者以另一种聪明的方式进行。

你有什么聪明的方法可以巧妙地做到这一点吗? 提前致谢! 亲切的问候,弗雷德

现状:

public class xlsxreadtest {

        @BeforeTest
        public void setup() throws Exception {
        }

        @Test (priority = 1)
        public void Read_xslx1() throws IOException {

        FileInputStream fis = new FileInputStream("./files/Test.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheetAt(0); 
        String text1 = sheet.getRow(2).getCell(1).toString();
        System.out.println(text1);
    }

        @Test (priority = 2)
        public void Read_xslx2() throws IOException {

        FileInputStream fis = new FileInputStream("./files/Test.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheetAt(0); 
        String text2 = sheet.getRow(3).getCell(1).toString();
        System.out.println(text2);
    }

    @AfterTest
    public void afterTest() {
        System.out.println("AfterTest : Driver close");
        driver.close();
    }
}

想要这样的东西,我只需要调用 Excel 方法或任何其他方法一次。

public class xlsxreadtest {

        @BeforeTest
        public void setup() throws Exception {
            FileInputStream fis = new FileInputStream("./files/Test.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            XSSFSheet sheet = workbook.getSheetAt(0);
        }

        @Test (priority = 1)
        public void Read_xslx1() throws IOException {
            
        String text1 = sheet.getRow(2).getCell(1).toString();
        System.out.println(text1);

    }

        @Test (priority = 2)
        public void Read_xslx2() throws IOException {
            
        String text2 = sheet.getRow(3).getCell(1).toString();
        System.out.println(text2);
    }

    @AfterTest
    public void afterTest() {
        System.out.println("AfterTest : Driver close");
        driver.close();
    }
}

您可以使局部变量 sheet 成为实例变量:

public class xlsxreadtest {
        XSSFSheet sheet;

        @BeforeTest
        public void setup() throws Exception {
            FileInputStream fis = new FileInputStream("./files/Test.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            sheet = workbook.getSheetAt(0);
        }

之后您可以从您的测试方法中引用它:

@Test (priority = 1)
public void Read_xslx1() throws IOException {
    String text1 = sheet.getRow(2).getCell(1).toString();
    System.out.println(text1);
}

@Test (priority = 2)
public void Read_xslx2() throws IOException {
    String text2 = sheet.getRow(3).getCell(1).toString();
    System.out.println(text2);
}