Home > front end >  Java Selenium how to set a dynamic variable for new driver
Java Selenium how to set a dynamic variable for new driver

Time:12-14

I know that it is in not possible in java to use variables from conditional Blocks. But I dont know what to do. When I do it like this I get an error for the code after the if statements:

public static void startDriver(String preferredBrowser) throws Exception{
    Webdriver driver;

    if(preferredBrowser.equals("Firefox")){

    } 
    else if(preferredBrowser.equals("Edge")){

    }
    else{
        System.setProperty("webdriver.chrome.driver",  driverPath);
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);

        driver = new ChromeDriver(options);
    }
    driver.manage().window().maximize();
    driver.get(website);

}

This what I tried to fix it but now it does open me two drivers at once:

public static void startDriver(String preferredBrowser) throws Exception{
    System.setProperty("webdriver.chrome.driver",  driverPath);
    WebDriver driver = new ChromeDriver();
    if(preferredBrowser.equals("Firefox")){

    } 
    else if(preferredBrowser.equals("Edge")){

    }
    else{
        System.setProperty("webdriver.chrome.driver",  driverPath);
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);

        driver = new ChromeDriver(options);
    }
    driver.manage().window().maximize();
    driver.get(website);

}

I hope you can help me out.

Best Regards

Christian

CodePudding user response:

You can initialize driver type for each preferredBrowser as following:

public static void startDriver(String preferredBrowser) throws Exception{
    Webdriver driver;

    if(preferredBrowser.equals("Firefox")){
        driver = new FirefoxDriver();
    } 
    else if(preferredBrowser.equals("Edge")){
            driver = new EdgeDriver();
    }
    else{
        System.setProperty("webdriver.chrome.driver",  driverPath);
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);

        driver = new ChromeDriver(options);
    }
    driver.manage().window().maximize();
    driver.get(website);
}
  • Related