3

是否可以在页面对象模型中处理动态元素?

例子:

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("url");
        Home_Page homepage = PageFactory.initElements(driver, Home_Page.class);
        homepage.inputField.sendKeys("xpathParameter", "sendKeysVal"); 
}
4

2 回答 2

2

不可能以您想要的方式实现,因为无法动态地将值传递给 Java - Java Annotations 以动态方式提供的值的注释。

但是,您可以实现相同的替换 your|class field + annotation| 使用 |方法|:

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"); 
    }
于 2018-10-31T14:59:12.743 回答
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();
于 2020-03-03T14:39:36.773 回答