如何在Selenium测试方法中传递"By"和String?

LVN*_*LVN 0 java selenium selenium-webdriver

所以我想为我的方法传递两个东西,String - 这将是一个属性名称和By - 这将允许选择应该搜索什么标准元素.简单的例子:

public static WebElement getElement(By by) {
    return driver.findElement(by);
}
Run Code Online (Sandbox Code Playgroud)

但这会迫使我这样使用它:

element = getElement(By.className(properties.getProperty("class")));
Run Code Online (Sandbox Code Playgroud)

虽然我想这样使用它:

element = getElement(By.className, "class");
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我认为像这样的简单代码可以工作,但遗憾的是它会返回错误

"by(String)未定义"

public static WebElement getElement(By by, String string) {
    return driver.findElement(by(properties.getProperty(string));
}
Run Code Online (Sandbox Code Playgroud)

编辑:我决定使用:

public static String useProperty(String propertyName) {
    return properties.getProperty(propertyName);
}
Run Code Online (Sandbox Code Playgroud)

不完全是我想要处理它,但它确实可以简化和提高代码的可读性.

Guy*_*Guy 6

这是不可能的,By.className()是一个接收String参数的方法.这String用于初始化内部类By.ByClassName,这是返回的By.

你可以构建switch case来处理这个问题

public static WebElement getElement(String string) {
    By by = null;
    String locator = properties.getProperty(string);

    switch (string) {
        case "class":
            by = By.className(locator);
            break;
        case "id":
            by = By.id(locator);
            break;
    }

    return driver.findElement(by);
}
Run Code Online (Sandbox Code Playgroud)

  • @RatmirAsanov谢谢.我看到了编辑,`switch`需要在`string`上,而不是`locator`. (2认同)
  • 是的,对不起,这是我的错. (2认同)