我正在尝试创建一个网页的自动测试。网页有一个筛选器窗体和一个表格。表有5-6种不同的数据呈现方式。
我为每种数据表示方式创建了PageObjects (都是表,只是有不同的列)。现在我有了这个通用的Pageobject,它可以查找表并查询其中的行。
但是我不能让这段代码去读取表中的所有行。
public <T> List<T> getAllRows(){
List<AbstractTableRow> allRows = table.findElements(By.xpath("//tr[@role='row']").className("jqgrow")).stream()
.map(AbstractTableRow::new).collect(Collectors.toList());
if(allRows != null) {
return (List<T>)allRows;
}
return null;
}
AbstractTableRow是所有其他行的父行。但它并不是真正的抽象类(我尝试过这种方式,最终陷入了泛型+反射的混乱事务中,最终没有起到作用)。所以现在我需要一些方法来向下转换父类到子类,或者有人可以给出一个有反射和泛型的例子,这样就可以让AbstratTableRow变得抽象了。所有的表行都是以WebElement类型传入的,所有的行对象都有
public SomeRow(WebElement element)
作为构造函数。方法需要返回List,其中SomeRow是5-6行类型之一。
发布于 2017-10-18 20:46:37
听起来您需要一个工厂类来生成实现TableRow接口(或扩展抽象AbstractTableRow类)的对象。
这通常是这样做的:
public interface TableRow {
/*methods..*/
}
public class NiceRow implements TableRow {
public NiceRow(WebElement element) {
//implementation
}
/*Implementation..*/
}
public class CuteRow implements TableRow {
public CuteRow(WebElement element) {
//implementation
}
/*Implementation..*/
}
public class TableRowFactory {
public static TableRow getRow(WebElement element) {
switch(element.getAttribute("class")) {
case "nice":
return new NiceRow(element);
/*...*/
}
}
}
现在,您可以获取一个工厂对象并使用它来生成行:
TableRowFactory factory = new TableRowFactory();
List<TableRow> allRows =
table.findElements(By.xpath("//tr[@role='row']")).stream()
.map(element -> factory.getRow(element))
.collect(Collectors.toList());
编辑类:请注意,getAttribute(“”)很可能会产生比单个类更多的东西,并且在我的代码中仅用于区分不同类的示例目的。
发布于 2017-10-19 16:06:24
您可以传递concrete SomeRow type
的类。此外,您还可以将RowTable切换为抽象,它将包含一个构造函数,该构造函数将WebElement作为单个参数,它将在子类型中被重载。(我认为这已经存在)。
public static <T extends RowTable> List<T> getTableData(Class<T> clz) throws Exception {
List<WebElement> elems = .....Your query....;
Constructor<T> cont = clz.getConstructor(WebElement.class);
List<T> data = elems.stream().map(e -> {
T type = null;
try {
type = cont.newInstance(e);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
return type;
}).collect(Collectors.toList());
return data;
}
称之为like - getTableData(ConcreteRow.class)
https://stackoverflow.com/questions/46810166
复制相似问题