首页 > 解决方案 > 每次测试用例运行时从 Excel 文件中读取不同的值

问题描述

我已经创建了一个包含一些代码的 excel 文件,并且我正在使用 RepeatRule 类在一个类中执行我的测试用例 100 次。每次运行测试时,我都需要使用不同的 100 个代码,而不是一次又一次地使用相同的代码。下面是我的代码

@Test

@Repeat(2)

public void Test() throws Exception {

    Success.setUp();
    Success.allowcokkies();


        //Success.Ecoomerecemain();
    File source = new File("/Users/test/Downloads/Voucher-codes.xlsx");
    FileInputStream input = new FileInputStream(source); // Read Excel Data
    XSSFWorkbook wb = new XSSFWorkbook(input);

    XSSFSheet sheet = wb.getSheetAt(0);
    int noOfColumns = sheet.getRow(0).getLastCellNum();

        System.out.println(noOfColumns);
        String[] Headers = new String[noOfColumns];
        int j=0;
        Headers[j] = sheet.getRow(0).getCell(j).getStringCellValue();
        Success.getDriver().findElement(By.xpath("//*[@id=\"code\"]")).sendKeys(sheet.getRow(0).getCell(j).getStringCellValue());// Enter Coupon
        Thread.sleep(2000);
    }
    @After
            public void testdown()
    {
 Success.getDriver().quit();

这是重复类代码: public class RepeatRule implements TestRule {

public static class RepeatStatement extends Statement {
    private final Statement statement;
    private final int repeat;

    public RepeatStatement(Statement statement, int repeat) {
        this.statement = statement;
        this.repeat = repeat;
    }

    @Override
    public void evaluate() throws Throwable {
        for (int i = 0; i < repeat; i++) {
            statement.evaluate();
        }
    }

}

@Override
public Statement apply(Statement statement, Description description) {
    Statement result = statement;
    Repeat repeat = description.getAnnotation(Repeat.class);
    if (repeat != null) {
        int times = repeat.value();
        result = new RepeatStatement(statement, times);
    }
    return result;
}

}

使用重复规则时如何每次读取不同的代码?

标签: seleniumjunit

解决方案


执行此操作的简单方法是 JUnit 5 参数化测试。将您的 Excel 工作表另存为 csv 并使用以下测试方法:

  @ParameterizedTest
  @CsvFileSource(resources = "/Users/test/Downloads/Voucher-codes.csv", numLinesToSkip = 1)
  void testVoucher(String coupon) {
...
    Success.getDriver().findElement(By.xpath("//*[@id=\"code\"]")).sendKeys(coupon);// Enter Coupon
...
  }

JUnit 4 也可以进行参数化测试。JUnit Wiki中描述了一个示例。您甚至可以将 Excel 工作表用作您的 POI 代码的数据提供者。

另一种解决方案是使用@BeforeEach,您可以在其中更新couponIndex测试类中的优惠券字段并通过该字段的值访问正确的行。

        Success.getDriver().findElement(By.xpath("//*[@id=\"code\"]")).sendKeys(sheet.getRow(couponIndex).getCell(j).getStringCellValue());// Enter Coupon

我建议使用参数化测试。


推荐阅读