I run tests using WebDriver, when the test fails, the browser does not close. On a Windows machine, this is a huge problem because I have multiple instances of IEDriver that are still running in the background.
I tried the try / catch statement, which also does not work. If the test fails, the browser still remains open. Any help would be greatly appreciated.
The try catch statement looks something like this:
try { Assert.something(something something dark side); driver.quit(); } catch(Exception e) { System.out.println(e) driver.quit(); }
My complete code is below:
public class ClickAddMedication { Browser browser = new Browser(); public void addMedication(String driverName) { //Open Browser and navigate to page WebDriver driver = browser.getDriver(driverName); driver.manage().window().maximize(); driver.get("http://someIP:8080/hmp_patient/index.html"); //Click Add Medication button WebElement addBtn = driver.findElement(By.id("add-btn")); addBtn.click(); //Verify Add Medication page has loaded successfully WebElement rxBtn = driver.findElement(By.className("icon-rx")); WebElement otcBtn = driver.findElement(By.className("icon-otc")); WebElement herbBtn = driver.findElement(By.className("icon-herb")); Assert.assertEquals(true, rxBtn.isDisplayed()); Assert.assertEquals(true, otcBtn.isDisplayed()); Assert.assertEquals(true, herbBtn.isDisplayed()); driver.quit(); } @Test(groups = {"functionalTests.FF"}) public void test_AddMedication_FF() { addMedication("firefox"); } @Test(groups = {"functionalTests.iOS"}) public void test_AddMedication_iOS() { addMedication("iOS"); } }
I run tests using the testng.xml file and would like to close the browser regardless of whether the test passes.
Below is my Browser class:
public class Browser { public WebDriver getDriver(String driverName) { WebDriver driver = null; if(driverName == "firefox") { driver = new FirefoxDriver(); } else if(driverName == "chrome") { File chromeFile = new File ("C:/webdrivers/chromedriver.exe"); System.setProperty("webdriver.chrome.driver", chromeFile.getAbsolutePath()); driver = new ChromeDriver(); } else if(driverName == "ie") { File ieFile = new File("C:/webdrivers/IEDriverServer.exe"); System.setProperty("webdriver.ie.driver", ieFile.getAbsolutePath()); driver = new InternetExplorerDriver(); } else if(driverName == "iOS") { try { driver = new RemoteWebDriver(new URL("http://localhost:3001/wd/hub"), DesiredCapabilities.ipad()); } catch (MalformedURLException e) { e.printStackTrace(); } } return driver; } }
source share