是否可以处理页面对象模型中的动态元素?
示例:
package pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class Home_Page {
WebDriver driver;
public Home_Page(WebDriver driver) {
this.driver = driver;
}
@FindBy(how=How.XPATH, using = "//input[@name = '%s']")
public WebElement inputField;
}
我想通过我的测试方法传递输入的名称属性值。
package scripts;
@Test
public void test(){
driver.get("http://play.krypton.infor.com");
Home_Page homepage = PageFactory.initElements(driver, Home_Page.class);
homepage.inputField.sendKeys("xpathParameter", "sendKeysVal");
}
答案 0 :(得分:1)
无法实现所需的方式,因为无法动态地将值传递给Java中的注释-Java Annotations values provided in dynamic manner。
但是,您可以通过替换| class字段+注释|来实现相同的效果使用|方法|:
package pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class Home_Page {
WebDriver driver;
public Home_Page(WebDriver driver) {
this.driver = driver;
}
public WebElement inputField(String name) {
return this.driver.findElement(String.format(By.xpath("//input[@name = '" + name + "']");
}
}
package scripts;
@Test
public void test(){
driver.get("http://play.krypton.infor.com");
Home_Page homepage = PageFactory.initElements(driver, Home_Page.class);
homepage.inputField("xpathParameter").sendKeys("sendKeysVal");
}
答案 1 :(得分:0)
如果您想使用findBy
查找元素并动态提供pagename
,这种事情应该会有用。
import org.openqa.selenium.By;
public class CreateLocators {
public static By buildByObject(String pageName, String fieldName) {
try {
Class<?> clas = Class.forName("pageobjects." + pageName);
Object obj = clas.newInstance();
return new Annotations(obj.getClass().getDeclaredField(fieldName)).buildBy();
} catch (NoSuchFieldException e) {
return null;
}
}
}
在StepDef
中,您应该这样做:
byElem = CreateLocators.buildByObject(pageName, desiredElementNameInPO);
elem = driver.findElement(byElem);
elem.click();