您可以使用WebDriver Extensions框架创建自定义 WebElements,该框架提供了实现 WebElement 接口的 WebComponent 类
创建您的自定义 WebElement
public class Table extends WebComponent {
@FindBy(tagName = "tr")
List<Row> rows;
public Row getRow(int row) {
return rows.get(row - 1);
}
public int getTableSize() {
return rows.size();
}
public static class Row extends WebComponent {
@FindBy(tagName = "td")
List<WebElement> columns;
public WebElement getCell(int column) {
return columns.get(column - 1);
}
}
}
...然后使用 @FindBy 注释将其添加到您的 PageObject 中,并在调用 PageFactory.initElements 方法时使用 WebDriverExtensionFieldDecorator
public class PermissionPage {
public PermissionPage(WebDriver driver) {
PageFactory.initElements(new WebDriverExtensionFieldDecorator(driver), this);
}
@FindBy(id = "studyPermissionsTable")
public Table permissionTable;
@FindBy(id = "studyPermissionAddPermission")
public WebElement addPermissionButton;
}
...然后在您的测试中使用它
public class PermissionPageTest {
@Test
public void exampleTest() {
WebDriver driver = new FirefoxDriver();
PermissionPage permissionPage = new PermissionPage(driver);
driver.get("http://www.url-to-permission-page.com");
assertEquals(25, permissionPage.permissionTable.getTableSize());
assertEquals("READ", permissionPage.permissionTable.getRow(2).getCell(1).getText());
assertEquals("WRITE", permissionPage.permissionTable.getRow(2).getCell(2).getText());
assertEquals("EXECUTE", permissionPage.permissionTable.getRow(2).getCell(3).getText());
}
}
甚至更好地使用WebDriver Extensions PageObject 实现
public class PermissionPage extends WebPage {
@FindBy(id = "studyPermissionsTable")
public Table permissionTable;
@FindBy(id = "studyPermissionAddPermission")
public WebElement addPermissionButton;
@Override
public void open(Object... arguments) {
open("http://www.url-to-permission-page.com");
assertIsOpen();
}
@Override
public void assertIsOpen(Object... arguments) throws AssertionError {
assertIsDisabled(permissionTable);
assertIsDisabled(addPermissionButton);
}
}
和具有 WebElements 的静态断言方法的 JUnitRunner
import static com.github.webdriverextensions.Bot.*;
@RunWith(WebDriverRunner.class)
public class PermissionPageTest {
PermissionPage permissionPage;
@Test
@Firefox
public void exampleTest() {
open(permissionPage);
assertSizeEquals(25, permissionPage.permissionTable.rows);
assertTextEquals("READ", permissionPage.permissionTable.getRow(2).getCell(1));
assertTextEquals("WRITE", permissionPage.permissionTable.getRow(2).getCell(2));
assertTextEquals("EXECUTE", permissionPage.permissionTable.getRow(2).getCell(3));
}
}