java - TestNG 参数无法识别字符串参数

标签 java selenium selenium-webdriver testng

我正在尝试运行 Selenium 脚本,并可选择使用 chrome 或 headless 驱动程序运行它。这可能不是实现这一点的正确方法,但这是我的第一个想法。解决方案可能是完全避免这种情况......

在设置方法中,我使用 TestNG 参数来定义我想要测试运行的环境以及我想要使用的驱动程序。 @Optional 标签用于在未提供时定义默认值。

public class Test1 {

@Parameters({"envDomain","driverName"})
@BeforeTest
public void setUp(@Optional("alpha1")String envDomain, @Optional("chrome")String driverName) {
    PropertiesCollection.selectDriver(driverName);
    PropertiesCollection.env_domain = envDomain;
}

PropertiesCollection.selectDriver() 方法采用字符串名称来决定将驱动程序设置为什么。

public class PropertiesCollection {
public static WebDriver driver;
public static WebDriverWait wait;
public static String env_domain;

public static void selectDriver(String driverName) {

    if (driverName == "chrome") {
        String projectPath = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.driver", projectPath + "\\configs\\WebDrivers\\chromedriver_win32\\chromedriver.exe");
        PropertiesCollection.driver = new ChromeDriver();
    }

    if (driverName == "headless") {
        PropertiesCollection.driver = new HtmlUnitDriver();
    }

}

无法在第一个 if 语句中设置驱动程序。当我手动输入字符串“chrome”时,它似乎按预期工作。我不确定为什么在使用 TestNG 的“chrome”时它不起作用。当我通过调试器运行它时,看起来 driverName 设置为“chrome”,但 if 语句仍然被跳过。

有效的示例:

public class Test1 {

@Parameters({"envDomain"})
@BeforeTest
public void setUp(@Optional("alpha1")String envDomain) {
    PropertiesCollection.selectDriver("chrome");
    PropertiesCollection.env_domain = envDomain;
}

envDomain 标记也按预期工作,因此我不确定为什么 driverName 参数会以不同的方式工作。

最佳答案

好的,我可以通过更改 if 语句中的条件来解决我的问题。

public class PropertiesCollection {
public static WebDriver driver;
public static WebDriverWait wait;
public static String env_domain;

public static void selectDriver(String driverName) {

    if (driverName.equals("chrome")) {
        String projectPath = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.driver", projectPath + "\\configs\\WebDrivers\\chromedriver_win32\\chromedriver.exe");
        PropertiesCollection.driver = new ChromeDriver();
    }

    if (driverName.equals("headless")) {
        PropertiesCollection.driver = new HtmlUnitDriver();
    }

}

其他人也许能够更深入地解释为什么它有效而原始版本无效。但我猜测这与询问参数是否等于对象本身或者是否等于字符串值有关...

关于java - TestNG 参数无法识别字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60764224/

相关文章:

java - Selenium CTRL 和单击不起作用?

java - 通过覆盖 toString() 能够仅打印 ArrayList 中的部分对象

java - 有什么比 jad 更准确​​的反编译器可以让 Eclipse 摆脱 <-MISALIGNED ->?

Java递归斐波那契值

java - JAR 可执行文件的优缺点

c# - Selenium PhantomJsDriver、C#、SendKeys 无法正常工作

selenium - 创建新的 WebDriver 会导致 StackOverflowError

python - 在 Python 中使用代理运行 Selenium Webdriver

python - 无法从网站收集链接(Python)

java - 无法使用 Selenium 获取 google 新闻页面中的新闻文章链接