selenium - 每次测试用例运行时从 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;
}
}
使用重复规则时如何每次读取不同的代码?
解决方案
执行此操作的简单方法是 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
我建议使用参数化测试。
推荐阅读
- actions-on-google - 帐号关联授权网址
- python - 从过程调用 cx_oracle python 获取结果数据
- python - 从另一个注入的对象创建一个对象会破坏依赖注入吗?
- wordpress - WooCommerce Rest api 创建/更新产品变化问题
- reactjs - React 三元运算符首先显示“:”块。为什么?
- java - 为什么我的代码绕过了我的 else if 语句?
- java - 使用 Instant.parse 解析 2018-05-01T00:00:00 日期时出错
- android - 如何通过向下滚动来增加片段的高度?
- jquery - 如何在js树中同时显示颜色和删除线?
- amazon-cloudwatch - Micronaut:记录器未出现在 AWS Cloudwatch 和 Java 应用程序中未在本地运行