每次运行测试用例时,都要从Excel文件中读取不同的值

问题描述 投票:0回答:2

我用一些代码创建了一个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实现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;
}

}

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

selenium junit
2个回答
0
投票

执行此操作的简单方法是进行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

我建议使用参数化测试。

© www.soinside.com 2019 - 2024. All rights reserved.