Posted in Automation Testing

Selenium: Cleaning up WebDriver instances using Java

While working with UI test automation, Selenium being most popular choice, people use it quite heavily.

However out of many best practices, the Webdriver clean up process is also critical.

Why?

  1. If WebDriver is not closed properly, it still remains active in the system and consumes memory, which leads the system slow.
  2. This issue becomes bottleneck while working with massive parallel tests and the system can not handle tests properly due to memory leakage happened due to these unattended WebDriver processes.
  3. Even though we use driver.quit(), it will only get executed if the test gets executed till the end , but if the test fails abruptly due to some issue, the quit() method do not close the WebDriver process.

Solution:

Just like we write driver.quit() for each Test we also need to include the process termination code.
Mainly we launch fresh WebDriver instances every time for each Test hence we keep driver.quit() in @AfterMethod.

However we can not keep Terminate process code here because, if we are running parallel Tests, it might kill those too. So it is better to keep the process termination script at the very end, when all the Tests are executed.

This can be in @AfterSuite .
Below is the code for Java:

  public static void terminateWebDriverProcess() {
        log.info("<<< WebDriver process cleanup >>>");
        try {
            if (System.getProperty("os.name").contains("Windows")) {
  Process process = Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe /T");
  process.destroy();
  log.info("All active WebDriver processes terminated !");
            } else {
                log.info("No active WebDriver process found!");
            }
        } catch (Exception e) {
            log.info("<<< Error occured while cleaning up WebDriver process." + e);

        }

Note:
– you can alter the script if you are on Mac or Linux.
– Replace log.info() with SYSOUT if logger is not implemented.

Leave a comment