5

我正在尝试在 Java 中使用Page Object模式,但在使用@FindBy/XPath时遇到了一些问题。

早些时候,我在 Groovy 中使用了以下构造:

driver.findElement(By.xpath("//td[contains(text(),'$SystemName')]")).click()

Here, SystemName is a parameter that can be different. 

现在,我想做同样的事情,但要按照 Java 中的页面对象范式:

public class ManagedSystems {

    private WebDriver driver;

    @FindBy(id="menu_NewSystem")
    private WebElement menuNewSystem;

    @FindBy (xpath = "//td[contains(text(),'$SystemName')]")  // ??? How to use SystemName from deleteSystem method (below)?
    private WebElement plantSystemName;

    ....

    public SystemHomePage deleteSystem (String systemName) {

        plantSystemName.click();

    }

}

在我的测试中,我调用了 deleteSystem:

SystemHomePage.deleteSystem("Firestone");

问题:如何将@FindBy 表示法链接到为 deleteSystem 指定的 PlantSystemNameSystemName

谢谢,浣熊

4

4 回答 4

6

我为此使用了另一种解决方法,即使使用页面工厂,我们也可以使用动态 xpath。

解决方案:添加任何静态父元素的xpath,并使用动态路径引用子元素。在您的情况下,//td[contains(text(),'$SystemName'),td 的父元素可能是 'tr' 或 'table'。如果表是静态的,请使用以下代码:

@FindBy(xpath = "<..table xpath>")
public WebElement parentElement; 

public WebElement getDynamicEmement(String SystemName){
  parentElement.findElement(By.xpath("//tr/td[contains(text(),'"+SystemName+"')]"))
}

现在在您的脚本中,首先访问表(以便将其引用加载到内存中),然后调用 getDynamicElement 方法。

waitForElement(parentElement)
getDynamicElement("System-A")
于 2018-06-05T14:14:06.067 回答
3

你不能这样做,注释是存储在类文件中的常量值。您无法在运行时计算它们。

请参阅可以在运行时确定注释变量吗?

于 2014-01-21T16:18:41.353 回答
3

感谢 Ardesco 和 Robbie,我提出了以下解决方案:

private String RequiredSystemNameXpath = "//td[contains(text(),'xxxxx')]";

private WebElement prepareWebElementWithDynamicXpath (String xpathValue, String substitutionValue ) {

        return driver.findElement(By.xpath(xpathValue.replace("xxxxx", substitutionValue)));
}

public void deleteSystem (String systemName) {


    WebElement RequiredSystemName = prepareWebElementWithDynamicXpath(RequiredSystemNameXpath, systemName);

    RequiredSystemName.click();

}
于 2014-01-23T13:42:59.300 回答
1

您正在使用页面对象工厂,而不仅仅是遵循页面对象模式。

您可以将页面对象创建为简单的类,并将标识符存储为私有变量,以及使用这些变量公开元素的方法,并且您仍然遵循页面对象模式。

看看这个;http://relevantcodes.com/pageobjects-and-pagefactory-design-patterns-in-selenium/

如果您的标识符只是变量,那么您可以使用任何您想要的操作

于 2014-01-21T18:13:36.687 回答