I am using testNG with selenium to write my test cases, I observed a strange problem that is When I run my test cases, and if any test case fails or any other exception occur in between the test case execution, the AfterTest method doesn't run but the driver.quit() method is written only inside the AfterTest method, so in this case it doesn't actually quits the driver and it keeps running even after test case execution is finished.

The other problem is that during the execution my application opens the new windows of browser but when the execution is successfully completed only single window is closed on which I am working and the other browser windows remained open. Kindly advice some good approach t o handle this situation.

4 Answers 4


If you set @AfterTest(alwaysRun=true) then the method will be called even if a test is failing.

From the documentation:

alwaysRun -> For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped.


Just as a complement for Julien Herr answer, you can use @AfterClass(alwaysRun = true) too.

In my project I prefer AfterClass because this way I can run all tests of a class in a single instance of the browser instead of opening and closing for each test.


You need to try and catch exceptions when your test fails, when handling your test failure exceptions, you can do some test cleaning up there, including close your browser instance.

  • You will need to refactor your code to achieve this.

I do not understand your second problem, can you please add more info?

  • In the second problem, my test executions opens a lot of browser windows as part of application functionality, but after execution I only calls driver.quit() which closes only single window, So How can I close all windows once my execution is complete? Jan 25, 2017 at 6:48
  • are your tests running in sequence? it is a good practice to close off one window once you are done with it, instead of shutting all of them down in one go.
    – Yu Zhang
    Jan 25, 2017 at 6:50
  • no just think I have only this one test case, no parallel test cases and all Jan 25, 2017 at 7:00

Wrapped your test steps in each test case in

 try {
    ... your test steps 
    } catch (NoSuchElementException e) { driver.quit();};

If your test case will be catch some exception, your browser will automatically close.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.