When using Selenium with a testing framework such as JUnit or TestNG, it is better to put selenium.stop() in the "closing method"(i.e. @After*) instead of in the test method itself. In this way, if tests failed, then the testing framework will be able to close the browser. Thus, you will save a lot of computer resources if your tests are opening and closing the browser thousands of times.
Code below show that TestNG will close the browser even the method failed.
/** * ShowCloseBrowser.java * Show that even though the test method fail, TestNG will close the browser. * @Author: Xuan Ngo */ import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertTrue; import com.thoughtworks.selenium.DefaultSelenium; @Test(sequential=true) public class ShowCloseBrowser { private DefaultSelenium selenium = null; @BeforeMethod public void runBeforeEachTestMethod() { final String sServerHost = "localhost"; final int iServerPort = 4444; final String sBrowserType = "*iexplore"; final String sBaseUrl = "http://www.google.ca/"; this.selenium = new DefaultSelenium(sServerHost, iServerPort, sBrowserType, sBaseUrl); this.selenium.start(); // Start selenium. this.selenium.open("http://www.google.ca/index.html"); // Open the main google webpage. } @AfterMethod public void runAfterEachTestMethod() { this.selenium.stop(); // Close browswer. } @Test(description="Show that TestNG will close the browser even the test fail.") public void myFailedTest() { assertTrue(false, "Explicitly fail this test."); } }