Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Selenide/Selenium中使用模板定位器的正确方法是什么?_Java_Unit Testing_Selenium_Uitest_Selenide - Fatal编程技术网

Java 在Selenide/Selenium中使用模板定位器的正确方法是什么?

Java 在Selenide/Selenium中使用模板定位器的正确方法是什么?,java,unit-testing,selenium,uitest,selenide,Java,Unit Testing,Selenium,Uitest,Selenide,我试图在UI测试中使用页面对象模式。许多示例假定通过定位器保存在类字段中。其他人建议保存WebElement或SelenideElement,如果您使用的是Selenide。尽管这两种方法都适用于硬编码定位器,但我不知道如何将其用于路径包含变量的定位器 例如,如何在类字段中保存此定位器 public SelenideElement getTotal(String type) { return $(By.xpath("//h4[contains(text(), '"+ type +"')]"

我试图在UI测试中使用页面对象模式。许多示例假定通过定位器保存在类字段中。其他人建议保存WebElement或SelenideElement,如果您使用的是Selenide。尽管这两种方法都适用于硬编码定位器,但我不知道如何将其用于路径包含变量的定位器

例如,如何在类字段中保存此定位器

public SelenideElement getTotal(String type) {
   return $(By.xpath("//h4[contains(text(), '"+ type +"')]");
}

我认为你的解决方案是正确的

我通常把它们放在我的页面对象的顶部,紧挨着其他选择器,就像你所做的那样。只需像使用SelenideElement字段一样使用该方法。比如:

private SelenideElement getTotalElementByType(String type) {
    return $(By.xpath("//h4[contains(text(), '"+ type +"')]");
}
但我会将其设置为私有或受保护,因为使用页面对象模式,您的测试脚本不应该知道页面对象上的WebElements

您可以公开访问的方法如下:

public int getTotalByType(String type) {
    string totalString = getTotalElementByType(type).getText();
    int total = //convert to int or whatever
    return total;
}

如果您希望与元素交互而不是获取值,则可以返回您希望转到的PageObject,而不是跟随POPattern:

实际上不需要将定位器保存到类字段。 页面对象不必声明类字段中的所有元素。Page对象是一个对象,这意味着它必须提供使用它进行操作的方法

因此,您的解决方案非常理想