javaseleniumquit

Not able to close instances of different browser using driver.quit


I have opened different browser instances and at the end i would like to close all the instances but when i use driver.close() or driver.quit() it is only closing the last instance of the browser. Please help.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;


public class showClose {

static WebDriver driver;

public showClose(WebDriver driver){
    this.driver=driver;
}

public static void main(String[] args) {

    showClose sc = new showClose(driver);
    sc.IE("http://www.msn.com");
    sc.Firefox("http://seleniumhq.org");
    sc.Chrome("http://google.com");

    driver.quit();

}

//Internet Explorer driver
public void IE(String URL){
    //Set the driver property for IE
    System.setProperty("webdriver.ie.driver",                 System.getProperty("user.dir")+"\\IEDriverServer.exe");

    DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();  
    ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);

    //Create object of Internet explorer driver
    driver = new InternetExplorerDriver(ieCapabilities);
    driver.get(URL);
}

//Firefox driver
public void Firefox(String URL){
    driver = new FirefoxDriver();
    driver.get(URL);
}

//Chrome driver
public void Chrome(String URL){
    System.setProperty("webdriver.chrome.driver",      System.getProperty("user.dir")+"\\chromedriver.exe");

    driver = new ChromeDriver();
    driver.get(URL);

}
}

Solution

  • Step1:

    In Main Class declare 'List list' Interface and declare it as 'Static'

    public static  List<WebDriver> drivers;
    

    Reason for Using List: It represents an ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index too. You can also add the same element more than once to a List.

    Step2: Now Create a Constructor in which we will point to out current driver from the Stored List of Drivers. (I assume my class name as Test)

    public Test()
    
    {
    this.drivers = new ArrayList<WebDriver>();
    }
    

    Step3:

    Add a WebDriver Instance to out ArrayList for drivers in all methods of IE, Firefox and Chrome.

    this.drivers.add(driver);
    

    Step4: In main class copy all the instances of stored drivers to an object and use that object to close all opened instances.

    for(WebDriver d : drivers)
    {
    d.quit();
    }