首页 > 解决方案 > 如何把一个方法我@beforeTest

问题描述

这里是一个 selenium/java 菜鸟。:) 试图了解有关 Test 注释的所有内容以及如何在所有类中使用方法(是否称为方法)。

我在下面有这个类,我在每个@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();
    }
}

标签: javaexcelseleniumtestng-annotation-test

解决方案


您可以将局部变量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);
}

推荐阅读