Reputation: 1974
When running chromeDriver I use a try/catch/finally statement to ensure that if any exceptions occur, my WebDriver will close properly. This works perfectly if a exception is thrown, however; in the case that the user force quits my application, the browser instance is not closed. This can lead to built up of unwanted google chrome threads running in the background.
How is it that I can ensure the browser closes when the user force quits my application?
Here is a example of the code:
public class WebDriverTest {
WebDriver driver;
WebDriverWait wait;
public WebDriverTest() {
System.setProperty("webdriver.chrome.driver", "res/chromedriver");
driver = new ChromeDriver();
this.wait = new WebDriverWait(driver, 1);
}
public static void main(String[] args) {
WebDriverTest main = new WebDriverTest();
main.test();
}
private void test() {
try {
driver.get("https://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("test");
} catch (Exception e) {
e.printStackTrace();
} finally {
//If force quit the browser is never closed
driver.quit();
}
}
}
Upvotes: 1
Views: 1306
Reputation: 1657
To ensure driver's close/quit methods are called on a force shutdown, you can use application's runtime shutdown hook. It's can be registered at a driver's init method and will be called upon any Ctrl-C/other force quit situation. Consider the following snippet.
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
driver.close();
driver.quit();
}));
Upvotes: 1
Reputation: 8506
Well, you seem to be doing the right job, by putting the quit into the finnaly block.
How about you execute this in the end of the test?
Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")
So you can kill chromedriver.exe.
Upvotes: 2