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

时间:2019-04-16 14:19:53

标签: selenium junit

我已经用一些代码创建了一个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();

这是重复的类代码:     公共类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;
}

}

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

1 个答案:

答案 0 :(得分: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

我建议使用参数化测试。

相关问题