最近开始研究 Selenium 页面对象模式。我了解 Selenium 页面对象模式和 PageFactroy 的概念。但令我困惑的是它缺乏灵 active 。例如,页面对象模式如何为简单的定位器参数提供支持?如何使用 Selenium 页面对象模式处理动态定位器?
为了更好地理解这个问题,请考虑以下场景。
我有我的登录页面。
public class LoginPage {
private final WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
By usernameLocator = By.id("username");
By passwordLocator = By.id("passwd");
By loginButtonLocator = By.id("login");
public HomePage loginAs(String username, String password) {
driver.findElement(usernameLocator).sendKeys(username);
driver.findElement(passwordLocator).sendKeys(password);
driver.findElement(loginButtonLocator).submit();
return new HomePage(driver);
}
}
我有我的主页。
public class HomePage {
private final WebDriver driver;
By usernameLocator = By.xpath("//span[contains(text(),'Welcome <LoggedInUserName>')]");
public HomePage(WebDriver driver) {
this.driver = driver;
}
public HomePage checkLoggedInUser(String username) {
// I want to parameterize the usernameLocator with the logged in username
driver.findElement(usernameLocator);
return this;
}
}
在主页中,我想检查包含文本“Welcome User1”的 span 标记。用户名可以根据登录用户进行更改。我想使用登录的用户名参数化主页中的 usernameLocator 。
我可以参数化按定位器并在运行时传递参数值吗?
最佳答案
您可以使用方法传递消息作为参数来执行此操作,该方法返回 By 对象,如下所示:
public By usernameLocator(String message) {
return By.xpath(String.format("//span[contains(text(),'%s')]", message));
}
在页面文件中需要的地方调用上述方法。
谢谢, 萨迪克
关于java - Selenium 页面对象模式定位器参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35053746/