SUBSCRIBE HERE TO GET POST UPDATES VIA EMAIL :

Delivered by FeedBurner

When to use close() and quit() methods in Selenium WebDriver

Many new learners are initially confused about when to use close() and when to use quit() method in Selenium WebDriver. close() method will close the current instance of the webdriver object reference. In simple word, It will close current window or tab on which your test is currently running. quit() methods will dispose webdriver object so it is also known as dispose method. In simple word, quit() methods will close all open browser tabs or windows.

First of all let's see how close() method works

How close() method work?
package TestPack;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class testClose {

 public static void main(String[] args) {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("webdriver.chrome.driver", exePath);
  WebDriver driver = new ChromeDriver();
  
  driver.get("https://only-testing-blog.blogspot.com/2014/01/textbox.html");
  driver.findElement(By.xpath("//b[contains(text(),'Open New Page')]")).click();
  //Close main browser window with title Only Testing: TextBox
  driver.close();
 }
}

Result : It will close browser window with title "Only Testing: TextBox" on which your webdriver test is currently running. Newly opened browser tab with title "Only Testing: MyTest" will remain as it is.

When to use close() method?
You can use close() method when you want to close only currently selected browser tab or window.

Now let's see usage of quit() method

How quit() method work?
package TestPack;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class testQuit {

 public static void main(String[] args) {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("webdriver.chrome.driver", exePath);
  WebDriver driver = new ChromeDriver();
  
  driver.get("https://only-testing-blog.blogspot.com/2014/01/textbox.html");
  driver.findElement(By.xpath("//b[contains(text(),'Open New Page')]")).click();
  //It will close all open browser tabs and windows
  driver.quit();
 }
}

Result : It will close all open browser tabs.


When to use quit() method?
You can use quit() method when you want to close all currently open browser windows or tabs.

No comments:

Post a comment