One question that crops up a lot is “Why is my browser not closing?”, and there are multiple reasons for this.
Close the Browser in a method that always runs
Tests fail.
If you have a driver.quit()
as the last statement in your @Test
and the test fails, then the browser will be left open.
Add the closing statement in an @After
, @AfterClass
(JUnit 4) or @AfterEach
, @AfterAll
(JUnit 5).
@AfterAll
public static void endSelenium(){
driver.close();
}
Did you Close
or Quit
or both
WebDriver has two methods:
.close()
.quit()
The documentation for close
says that it will close the browser if it is the last window that is closed.
quit
will close all windows.
But… drivers change and interpret this in different ways.
- For some Firefox releases, this did not happen. Therefore I used to use
close
, andquit
. - Recently, with Firefox, if I
close
and thenquit
an exception will be raised when Iquit
. - With ChromeDriver if I
close
andquit
then nothing untoward happens.
You can be ‘good’ and Use quit
when you know it is the last window you are working with. Or if you are working with a Driver Manager abstraction then you might want to stick the quit
in a JVM Shutdown.
A general purpose solution is to use both close
and quit
but wrap the quit
in a try
catch
block.
@AfterAll
public static void endSelenium(){
driver.close();
try{
driver.quit();
}catch (Exception e){
System.out.println("Browser closed already, " +
"did not need to quit after all");
e.printStackTrace();
}
}
And of course if we did something like this then we could delegate it off to an abstraction layer.
@AfterAll
public static void endSelenium(){
CloseDriver.now(driver);
}
Full Source
The full source for this is in my Webdriver Java FAQs project:
Specifically:
If you want to learn how to use Selenium WebDriver with Java then check out our online courses.