我正在尝试运行 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/