Selenium WebDriver

What is the latest version of Selenium?


What is locator and different locators in Selenium?

Locator can be termed as an address that identifies a web element uniquely within the webpage. Thus, to identify web elements accurately and precisely we have different types of locators in Selenium:

  1. Id
  2. Name
  3. LinkText
  4. Partial LinkText
  5. Tag Name
  6. Class name
  7. CSS
  8. xPath

What are the limitations of Selenium?

Technical challenges with Selenium are:

  1. Selenium supports only web based applications.
  2. It does not support the Bitmap comparison.
  3. For any reporting related capabilities have to depend on third party tools.
  4. No vendor support for tool compared to commercial tools like QTP/UFT.
  5. As there is no object repository concept in Selenium, maintainability of objects becomes difficult.

What’s the difference between “/” and “//” in xPath?

xPath is used to locate a web element based on its XML path. xPath can be used to locate HTML elements.

Single Slash (/) – Single slash is used to create Xpath with absolute path i.e. the xPath would be created to start selection from the document node/start node.

Double Slash (//) – Double slash is used to create xPath with relative path i.e. the xPath would be created to start selection from anywhere within the document.

What is Absolute and Relative xPath?

Absolute xPath: Writing the complete path of a specified element with tags using single forward slash (‘/’) is known as Absolute xPath. It is time consuming and lengthy. Here the single slash (‘/’) represents immediate child.

Example: html/body/div[7]/div[3]/div/div[2]/div[1]/span

Relative xPath: Writing the path of a specific element using double forward slash with parent tag (‘//’) is known as Relative xPath. Here the double slash (‘//’) represents any child also called as Descendants.

Example: //table[@class=’dataTable’]/tbody/tr[1]

What is WebDriver?

WebDriver is a component from Selenium to automate web applications, and in particular to verify that they work as expected. It aims to provide a friendly API that’s easy to explore and understand.

What are the different types of Drivers available in WebDriver?

The different drivers available in WebDriver are:

  1. FirefoxDriver
  2. InternetExplorerDriver
  3. ChromeDriver
  4. SafariDriver
  5. OperaDriver
  6. AndroidDriver
  7. IPhoneDriver
  8. HtmlUnitDriver

What is WebElement?

WebElement represents an HTML element. Generally, all operations on a web page will be performed through this WebElement.

How do you launch the browser using WebDriver?

The following syntax can be used to launch Browser:


System.setProperty(“webdriver.gecko.driver”, “C:\\Nagesh\\Lib\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();


System.setProperty(“”, “C:\\Nagesh\\Lib\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();


System.setProperty(“”, “C:\\Nagesh\\Lib\\IEDriverServer.exe”);
WebDriver driver = new InternetExplorerDriver();

How do you open the Gmail in Firefox browser?

The Code is:

WebDriver driver =new FirefoxDriver();

How do you open a site using chrome browser?

 public class ChromeBrowser{

public static void main(Stringargs[]){

//Set System property for chrome driver
WebDriver driver=new ChromeDriver();

How do you open a site using IE browser?

Public class IEBrowser{
publicstaticvoid main(Stringargs[]){

//Set System property for IE driver
WebDriver driver=new InternetExplorerDriver();

How can we get a text of a Web Eelement?

 getText() command is used to retrieve the inner text of the specified web element. The command doesn’t require any parameter but returns a string value.

Sample Code:

String strTxt=driver.findElement(“Text”)).getText();

How do you maximize the browser?

To maximize a web browser, WebDriver providers a built-in method and here is the syntax:

WebDriver driver =new FirefoxDriver();
//to maximize the browser

Write a code to get the title of a page?

To get the title, we will use getTitle() method and here is the code:

WebDriver driver =new FirefoxDriver();
//to get the title
String strTitle = driver.getTitle();
//to print the title

Write a code to enter and clear value in a text box?

Entering values in Text Box:
sendKeys() method is used to enter the value into the text boxes.


Clearing Values in Text Box:
clear() method is used to clear the text box.

driver.findElement(“txtboxname”)).clear() ;

Write a code to read the text box value?

By using, getAttribute() method we can get the value of the text box.

//to print the text

How do you get the typed text in a textbox?

Use getAttribute() method to get the value of a typed text in the textbox and pass “value” as an argument.


How can you find if an element is displayed on the screen?

The visibility of the WebElements can find using the following methods:

  1. isDisplayed()

Sample Code:





System.out.println(“Not Available”);


How do you print all links on a page?

List<WebElement> str= driver.findElements(By.tagName(“a”));


for (int i = 0; i < str.size(); i++) {



System.out.println(str.get(i).getText());  //str[i]



How do you print all dropdowns on a page?

List<WebElement> str= driver.findElements(By.tagName(“select”));


for (int i = 0; i < str.size(); i++) {

System.out.println(“dropdown locator is :”+str.get(i).getAttribute(“name”));


How do you verify if the checkbox or radio is selected or not?

By Using isSelected() method, we can identify whether it is selected or not. The return type of the method is Boolean. So if it returns ”True” then button is selected else it is not selected.

Boolean b =driver.findElement(By.xpath(“Xpath”)).isSelected();

Write a code to clear the contents of a textbox?

 driver.findElement(By.xpath(“xpath of the textbox”)).clear

How do you get Width & Height of a text box?

 public class Width_Height{

public static void main(String[] args){

WebDriver driver=new FirefoxDriver();
WebElement element=driver.findElement(By.xpath(“xpath of a textbox”));



How to check all checkboxes in a page?

 public class Check_all_checkbox{

public static void main(String[] args){
WebDriver driver=new FirefoxDriver();

List<WebElement> allchkBox=driver.findElements(By.xpath(“//input[@type=’checkbox’]”));



What is the use of deSelectAll() method?

It is used to deselect all the web elements which have been selected earlier.


What is the use of getOptions() method?

getOptions() is used to get all the values from the dropdown

What is the use of getAllSelectedOptions() method?

getAllSelectedOptions() is used to get only the selected values from the list dropdown

What is the difference between findElement() and findElements()?

findElement( ):

Find the first element within the current page using the locators.

Returns a single WebElement.

If element not found, will throw the exception like NoSuchElementException.

findElements( ):

Find all elements within the current page using the given locator.

Returns List of WebElements.

If element not found it will return empty List of WebElement object.

What is the difference between driver.close() and driver.quit()?

close(): close() method closes the child window.
quit(): quit() method closes the main browser and also all the windows that the program has opened.

How to capture screenshot in WebDriver?

 The sample code to take screenshot of webpage is:


How to capture screenshot in WebDriver for a failed case?

To get screenshot on test failure, we should put the entire code in try-catch block. In the catch block make sure to copy the above screenshot code.

Public class TakeScreenshot{

WebDriver driver;

public void start(){

public void test() throws Exception{
//find the element with wrong xpath, so control moves to catch block
driver.findElement(By.xpath(“Wrong Xpath”)).sendKeys(“Testing”);

}catch(Exception e){
//Takes the Screenshot and saves in the path mentioned when test fails
File scrFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);


How to refresh a web page using WebDriver?

The following are the various methods available in WebDriver to refresh the page:

  1. Using refresh() method:


  1. Using to() method:


  1. Using get() method:


  1. Using SendKeys method:

driver.findElement(By.xpath(“xpath”)).sendKeys(Keys.F5) ;

How do you navigate browser back and forward?

 //Navigate – Forward


//Navigate – Back

How do you handle alert pop-up?

By using “Alert” class you can handle pop-up’s. First move control to alert pop-up’s, then move back control to main window.
The Sample code is:

WebDriver driver=new FirefoxDriver();

//Move control to alert pop up
Alert alt=driver.switchTo().alert();
//to click “Ok”
//to click “Cancel”

How to perform right click using WebDriver?

Method 1: Using Actions class

// the element on which the right click to be performed
WebElement element=driver.findElement(By.xpath(“//a[@href=’username’]”));
Actions action=new Actions(driver);
//this will perform right click

Method 2: Using ContextClick()

WebElement element=driver.findElement(By.xpath(“//a[@href=’username’]”));
// Initialize Actions class object
Actions builder=new Actions(driver);
//ContextClick() is a method to right click

How do you perform drag and drop using WebDriver?

 Method 1:

Actions act=newActions(driver);
WebElement source=driver.findElement(By.xpath(“source xpath”));
WebElement target=driver.findElement(By.xpath(“target xpath”));
act.dragAndDrop(source, target).build().perform();

Method 2:


Method 3:


Write a code to upload a file?

 //Syntax – sendKeys(“file to be uploaded”);

driver.findElement(By.xpath(“xpath”)).sendKeys(“D:\\test.txt”) ;

What is the difference between getWindowHandles() and getWindowHandle( )?

getWindowHandles() – is used to get all the open browser from the current execution and its return type is Set<String>.
getWindowHandle() – is used to get the address of the current browser where the control is and return type is String.

How to switch between windows?

 Set<String> str = driver.getWindowHandles();

System.out.println(“The windows are :”+str);

Object[] s = str.toArray();







What is the difference between driver.get() and driver.navigate() methods?


driver.get() method is generally used to open the url.

It will wait till the whole page gets loaded.


driver.navigate() method is generally used to navigate to url.

It supports back, forward, and page refresh.

It will just navigate to the page but will not wait till the whole page gets loaded.

How do you handle iframes in selenium?

 public class Frame {

public static void main(String[] args) {

System.setProperty(“”, “C:\\Nagesh\\Lib\\chromedriver.exe”);

WebDriver driver=new ChromeDriver();









How do you simulate, mouse over, scroll down and scroll up actions?

 Actions a = new Actions(driver);

WebElement str = driver.findElement(By.xpath(“//*[@id=’highlight-addons’]”));


driver.findElement(By.linkText(“Hot Meals”)).click();





How to get colour of a text?

 String clr= driver.findElement(By.xpath(“//a[text()=’facebook’]”)).getCssValue(“color”);


How to hover the mouse on an element?

By using Actions class, you can move cursor to a particular element.

WebElement element=driver.findElement(By.xpath(“xpath of a element”));
Actions act=new Actions(driver);

Write a code to handle https website error in selenium?

 //Create ff profile

FirefoxProfile fp=new FirefoxProfile();

//pass ff profile as constructor
WebDriver driver=new FirefoxDriver(fp);

How do you send ENTER Key?

 WebDriver driver=new FirefoxDriver();


//Enter Key

How to perform double click using WebDriver?

 WebDriver driver=new FirefoxDriver();


//button to be double clicked
WebElement element=driver.findElement(By.xpath(“xpath”));
Actions act=new Actions(driver);

//double click

How to press Control+T action? Or How to open new tab in the browser?

WebDriver driver=new ChromeDriver();


Robot r = new Robot();





Write a code to print the number of links in a page?

 List<WebElement> str= driver.findElements(By.tagName(“a”));


for (int i = 0; i < str.size(); i++) {






How to disable cookies in browser?

 Public class Disable_Cookies{

public static void main(String[] args){

//disable cookies in firefox
//create firefox profile
FirefoxProfile fp=new FirefoxProfile();
//disable cookies
fp.setPreference(“network.cookie.cookieBehavior”, 2);
WebDriver driver=new FirefoxDriver(fp);

//disable cookies in chrome
ChromeOptions options=new ChromeOptions();
Map prefs=new HashMap();



How to handle dynamically changing xPaths?

You can handle dynamically changing xPaths by following ways:
1. Use starts with function


  1. Use contains function


Write a code to set browser width and height?

 Public class Browser_Height{

public static void main(String[] args){

WebDriver driver=new FirefoxDriver();

//set browser height=500 and width=500
Dimension d=new Dimension(500,500);


How do you load data from Properties files?

 Public class Prop_File{

public void propfile() throws IOException{

//create the properties object
Properties prop=new Properties();
FileInputStream fp=new FileInputStream(“D:\\”);

//load the file

WebDriver driver=new FirefoxDriver();
//load url from the properties file

 How to print data from notepad(txt file)

File f=new File(“E:\\data2.txt”);

FileReader fr=new FileReader(f);

BufferedReader br=new BufferedReader(fr);

String str;





 How to create and write data into txt file

  1. File f=new File(“E:\\data2.txt”);
    FileWriter fw=new FileWriter(f);
    BufferedWriter bw=new BufferedWriter(fw);

How do you download a file using selenium WebDriver?

Public class FileDownload{

public static void main(String[] args){

FirefoxProfile fp=new FirefoxProfile();
//the browser will not ask for save location & mime type of the file to be downloaded – text file here

WebDriver driver=new FirefoxDriver();
//click download link & file will automatically saved into system

How do you connect db using WebDriver?

Public class DB_Connection{

public static void main(String[] args) throws ClassNotFoundException,SQLException{

//Connection URL
String dbUrl=”jdbc:mysql://localhost:3306/userdb”;

//DB username and password
String Username=”root”;
String Password=”root”;

//Query to be used
String query=”select username from table_name;”;

//Load my sqljdbc driver

//Connect DB
Connection con=DriverManager.getConnection(dbUrl,Username,Password);

//Create Statement Object
Statement st=con.createStatement();

//Send Query to DB
ResultSet rs=st.executeQuery(query);

//while loop to print the result
String u_name=rs.getString(1);
//prints the username

//close db connection

How do you get X and Y coordinates of a WebElement?

//Get the co-ordinates
Point p=driver.findElement(By.xpath(“xpath of a webelement”)).getLocation();
//Print the co-ordinates

How will you get data from WebTable?

String str;



String[] s = str.split(“\n”);


int n=0;

for(int i=0; i<s.length; i++){

if(s[i].contains(“Hyderabad (HYD)”))








System.out.println(“Hyderabad is not available”);


Write a code to delete all the cookies of a browser?


How do you access the Firefox profiles in WebDriver?

Public class FF_Profile{

public static void main(String[] args){

//create object of profiles Ini class which holds all the profile of ff
ProfilesIni prof=new ProfilesIni();
//get the profile you want (from already existing one)
FirefoxProfile p=prof.getProfile(“user1″);

//pass the desired profile object as constructor
WebDriver driver=new FirefoxDriver(p);
//driver will open the url by using the user1 profile

What is the difference between xPath and DOM (Document Object Model)?

The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Objects in the DOM tree may be addressed and manipulated by using methods on the objects.


var element =document.getElementById(“intro”);

xPath, the XML Path Language, is a query language for selecting nodes from an XML document. In addition, xPath may be used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML document.



What is HTML UnitDriver?

HtmlUnitDriver is one of the drivers of Selenium WebDriver. HtmlUnitDriver and PhatomJsDriver are most popular headless browsers.

Html Unit Driver is currently the fastest and most lightweight implementation of WebDriver. As the name suggests, this is based on HtmlUnit. HtmlUnit is a java based implementation of a web browser without a GUI. HtmlUnit Driver is a well known Headless Browser driver. HtmlUnit Driver is similar to the other drivers such as Mozilla Firefox, Google Chrome, Internet Explorer but you couldn’t see the GUI of Html UnitDriver.

You can create a HtmlUnitWebDriver as shown below

1 WebDriver driver = new HtmlUnitDriver()

How do you enable JavaScript in HTML UnitDriver?

HtmlUnitDriver driver =new HtmlUnitDriver();


HtmlUnitDriver driver =new HtmlUnitDriver(true);

What is Thread.Sleep()?

The Thread.Sleep() method causes the currently executing thread to sleep for the specified number of milliseconds. Its standard wait

How to retrieve css properties of an element?

The values of the css properties can be retrieved using a getCssValue () method.


driver.findElement(“id“)).getCssValue(“name of css attribute”);

What is the difference between POI and JXL jars?

1 JXL supports only “.xls” format. (Excel 2003) POI jar supports all excel formats
2 JXL API doesn’t support rich text formatting POI API supports rich text formatting
3 JXL API is faster than POI API POI API is slower than JXL API

What is the difference between Assert and Verify?

Verify command will not stop execution of test case if verification fails. It will log an error and proceed with execution of rest of the test case.

Assert command will stop execution of test case if verification fails. It will log an error and will not proceed with execution of rest of the test case. We use assertions in scenarios where there is no point proceeding further if expected output is not matched.

Use assertions when you want to stop execution of a test case if expected output is not matched and use verification when you still want to proceed execution of a test case if expected output is not matched.

Give the example for method overloading in WebDriver?

frame(string), frame(int), frame(WebElement).

What are the different types of exception we get in WebDriver?

Exception Description
ElementNotVisibleException Element is present but not visible and can not be interacted with.
NoSuchElementException Element not present in DOM. Thrown by findElement(By by) &findElements(By by).
StaleElementReferenceException The reference to the element is now stale. It is no longer appears on the DOM of the page.
TimeoutException Exception thrown when a command does not complete in enough time.
InvalidCoordinatesException The co-ordinates provided to the interactions operation are not valid.
MoveTargetOutOfBoundsException The target provided to the action move() method is invalid – outside of the size of the window.
NoAlertPresentException When user tries to access alert when it is not present.
NoSuchFrameException Exception thrown when accessing the frame which is not present. (WebDriver.SwitchTo().frame())
NoSuchSessionException Thrown by any command being called after WebDriver.quit().
NoSuchWindowException Thrown when accessing the window which is not present (Thrown by WebDriver.SwitchTo().window()).
NoSuchContextException Thrown by WebDriver.SwitchTo().context().
InvalidCookieDomainException Thrown when attempting to add a cookie under a different domain than the current url.
UnableToSetCookieException Thrown when a driver fails to set cookie.
UnhandledAlertException Alert is present due to which the operation cannot be performed.
UnreachableBrowserException Problem with connection to browser due to closing of browser, invalid remote server address.
ConnectionClosedException Exception thrown when the connection to the SafariDriver is lost.
UnsupportedCommandException Used to indicate that a command used by the remote webdriver is unsupported.

What are the different types Waits in WebDriver?

Waiting provides some time interval between actions performed; mostly locating an element or any other operations to be performed on the element.

Implicit Wait:

Implicit wait tells Selenium instance to wait for specified amount of time before throwing an exception. If WebDriver cannot find an element, it will wait for specified amount of time. During this time, no attempt is made to find the element. After completion of specified time, WebDriver will try to find the element. If the element is not found then we get an exception.

Implicit wait can be implemented by using the code below:


Explicit Wait:

You can define to wait for a certain condition to occur before proceeding further test code execution.

Explicit wait can be implemented by using the code below:

WebDriverWait wait =new WebDriverWait(driver,20);

Fluent Wait:

Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. And you can ignore specific types of exceptions while waiting, such as NoSuchElement Exceptions when searching for an element on the page.

Fluent wait can be implemented by using the code below:

Wait wait=new FluentWait (driver);
.withTimeout(30, SECONDS);
.pollingEvery(5, SECONDS);

What is actions class in WebDriver?

Actions class is used to control the actions of mouse and complex user gestures.

Write the scenarios which cannot be automated using WebDriver?

Few scenarios cannot be automated using WebDriver. They are:

  1. Captcha
  2. Barcode Reader
  3. Bitmap Comparison


Explain how can you use recovery scenario (Exception handling) with Selenium?

You can use recovery scenario depends upon the programming language you use. If you are using Java then you can use exception handling. By using “Try Catch Block” within your Selenium WebDriver Java tests, you can handle exceptions.

How can you create html test report?

To create html test report there are three ways:

  1. TestNG: Using inbuilt default.html to get the HTML report. Also XLST reports from ANT, Selenium, TestNG combination
  2. JUnit: With the help of ANT
  3. Using our own customized reports by using XSL jar for converting XML content to HTML

What is EventFiringWebDriver?

To create html test report there are three ways:

  1. WebDriverEventListener: It’s an interface containing all unimplemented methods related to different events of WebDriver.

       2.AbstractWebDriverEventListener: It’s an abstract class which implements WebDriverEventListener interface and          provides empty implementation of all the methods defined in interface.

       3.EventFiringWebDriver: It’s a class which implements WebDriver interface.It has two important methods:

        a. Register (WebDriverEventListenereventListener) : The method is used to bind our WebDriver instance with custom WebDriverEventListener class to handle different events.

      b. Unregister (WebDriverEventListenereventListener) : The method is used to isolate the WebDriver instance from WebDriverEventListener class

What is TestNG listener and How to implement in Selenium?

In TestNG we can generate logs with the help of Listeners. Listeners implement the interface “org.testng.ITestListener”. There are methods which gives you real time information.

You can either extend ‘TestListenerAdapter’ or implement Interface ‘ITestListener’ which is a listener for test running.

By using TestNG listeners ‘ITestListener’ or ‘TestListenerAdapter’ we can change the default behaviour write our own implementation when a Test fails or Skips etc.

What is difference between WebDriver listener and TestNg listener?

TestNG Listeners are triggered at test level such as before starting the test, after the test or when test fails etc;

Whereas WebDriver Listener are triggered at component level such as before click, after click etc.

How to Zip a folder using WebDriver?


public class Zip_File{

public static void main(String[]args){

Zip zipFolder=new Zip();
//Folder to be zipped (Source)
File sourceFile=new File(“D:\\Test\\Source”);

//Zip file Destination location and Zipfile name
File destinationFile=new File(“D:\\Test\\”);

//Unzip location
File unzipLocation=new File(“D:\\Test\\Destination”);


//Creates a zip file,destinationFile);

//UnZip a file

}catch(IOException e){

How to encode or encrypt password in WebDriver?

import: org.apache.commons.codec.binary.Base64;

public class Encrypt_PWD{

//Create a ‘’ file and store password to be used
//Download Base64 jar file and add jar file in project as external jar.
/*Base64: Base64 is a group of similar binary-to-text encoding schemes
* that represent binary data in an ASCII string format
* by translating it into a radix-64 representation.
* The term Base64 originates from a specific MIME content transfer encoding.*/

public static void main(String[] args) throws IOException{

// Create FileInputStream Object
FileInputStream fileInput=new FileInputStream(newFile(“D:\\”));
// Create Properties object
Properties prop =new Properties();
//load properties file

// create Firebox object
WebDriver driver =new FirefoxDriver();
//Go to URL
//Maximize browser window
//Set timeout




//Print Encrypted Password
System.out.println(“Encrypted Password =: “+new String(Base64.encodeBase64(prop.getProperty(“password”).getBytes())));
//Print Decrypted Password
System.out.println(“Decrypted Password =: “+new String(Base64.decodeBase64(Base64.encodeBase64(prop.getProperty(“password”).getBytes()))));

//close firefox browser

How to get Date and Time of a specific timezone?

SimpleDateFormat df= new SimpleDateFormat(“yyyy/MMM/dd hh:mm:ss a”);

Date d =new Date();

String time = df.format(d);


How to highlight elements Selenium Webdriver using JavaScript?

public  void highlight(By locator) throws Exception



WebElement elem = driver.findElement(locator);

JavascriptExecutor je=(JavascriptExecutor)driver;

je.executeScript(“arguments[0].style.border=’3px solid blue’, elem);

} catch (RuntimeException localRuntimeException)


System.out.println(“Error in Highlighting the element :” + localRuntimeException.getMessage() + “Fail”);




Write a program to check if text is present on a page.

The solution to the above problem is to specify the location of FireFox in your script.
Here is a sample code:
WebDriver driver=new FirefoxDriver();

String pageSrc=driver.getPageSource();

String textToCheck=”cricket”;

Boolean is Text Present=pageSrc.contains(textToCheck);

//result will be true if the text is present in the page
System.out.println(“Result = “+isTextPresent);


What is TestNG?

TestNG is a testing framework and inspired from JUnit and NUnit by adding new functionalities which made TestNG more powerful than other frameworks.

What are the benefits of using TestNG?

The benefits are:

  1. Generate detailed HTML test reports
  2. Run test cases in group
  3. Parallel test execution
  4. Control test case execution order
  5. Parameterize Tests, etc.,

What is the difference between JUnit and TestNG?

No JUnit TestNG
1 The naming convention for annotation is a bit complicated for, e.g., “Before”, “After” and “Expected”. It is easier to understand annotations like “BeforMethod”, “AfterMethod” and “ExpectedException”.
2 JUnit does not have “Parameterized Test” or “Dependency Test” feature. TestNG use “dependOnMethods” to implement the dependency testing.
3 In JUnit grouping of test cases are not available. In TestNG, grouping of test cases is available.
4 For every @test, the Before method and After method are applicable It executes all the test methods in sequential order

List down TestNG Annotations?

TestNG annotations are:

@BeforeSuite:The annotated method will be run before all tests in this suite have run.

@AfterSuite: The annotated method will be run after all tests in this suite have run.

@BeforeTest: The annotated method will be run before any test method belonging to the classes.

@AfterTest: The annotated method will be run after all the test methods belonging to the classes.

@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.

@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.

@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.

@AfterClass: The annotated method will be run after all the test methods in the current class have been run.

@BeforeMethod: The annotated method will be run before each test method.

@AfterMethod: The annotated method will be run after each test method.

@DataProvider: Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.

@Factory: Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[].

@Listeners: Defines listeners on a test class.

@Parameters: Describes how to pass parameters to a @Test method.

@Test: Marks a class or a method as part of the test.

What are the different ways in which you can produce reports for TestNG results?

There are two ways to produce a report with TestNG, they are:

  1. Listeners: For a listener class to implement, the class has to implement the org.testng.TestListener interface. These classes are informed at runtime by TestNG when the test begins, finishes, skips, passes or fails.
  2. Reporters: For a reporting class to implement, the class has to implement an org.testng.Reporter interface. When the whole suite run ends, these classes are called. When called, the object consisting the information of the whole test run is delivered to this class.

What is @DataProvider annotation?

@DataProvider: Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.

Public class DataProviderExample{

public void setData(String username,String password){

System.out.println(“Username: “+username);

public Object[][] getData(){
//Rows – No of test iteration.
//Columns – No of parameters in test data.
Object[][] data=new Object[3][2];

// 1st row

// 2nd row

// 3rd row

return data;

How do you prioritize your test case in TestNG?

You can set priority for TestNG @Test annotated methods as bellow.

Using priority, We can control @Test method execution manner as per our requirement. That means @Test method with priority = 0 will be executed 1st and @Test method with priority = 1 will be executed 2nd and so on.

Sample Code:

Public class PriorityExample{

public void Test1(){
System.out.println(“This test will run first.”);

public void Test2(){
System.out.println(“This test will run third.”);

public void Test3(){
System.out.println(“This test will run second.”);

What is timeout in TestNG?

The maximum number of milliseconds the test should take.

Sample Code:

@Test(timeOut=1000)// time in milliseconds
public void timeOutExample(){
System.out.println(“Timeout test”);
The above test should be executed within 1000 milliseconds. Other test will be failed

How do you skip a test in TestNG?

@Test(enabled=false) annotation is used to skip a test case if it is not ready to test.

What is expected annotation?

We use “expected” with @Test annotation and specify the type of exceptions that are expected to be thrown when executing the test methods.

The below example which throws an exception called “ArithmeticException” when dividing two numbers with denominator value as 0. The test will pass since we handled the exception by “expected” annotation.

public void dividedByZeroEx(){
int e=1/0;
When you run the test without “(expected = ArithmeticException.class)”, then it will throw the exception “java.lang.ArithmeticException: / by zero”. And the test will fail.

public void dividedByZeroExample2(){
int e=1/0;

What is syntax to set test method dependency for multiple test methods?

We can set test method’s dependency on multiple test methods as bellow.
public void Logout(){
System.out.println(“Logout Test.”);

We set dependency on @Test methods to skip its execution if the depending on method fails.

How do you execute group test cases in TestNG?

We can execute only set of group and exclude another set. This gives us the maximum flexibility in divide tests and doesn’t require us to recompile anything if you want to run two different set of tests back to back. Groups are specified in testng.xml file.

Sample Code:

Public class groupExamples{

public void testCaseOne(){
System.out.println(“Regression Group”);

public void testCaseTwo(){
System.out.println(“Regression Group”);

public void testCaseThree(){
System.out.println(“Retest Group”);

public void testCaseFour(){
System.out.println(“Retest Group”);

How do you preserve order in TestNG?

By default, TestNG will run your tests in the order they are found in the XML file. If you want the classes and methods listed in this file to be run in an unpredictable order, set the preserve-order attribute to false.

How to use assertions in TestNG explain with one example?

There are many different assertions available In TestNG but few important assertions are:

  1. assertEquals
  2. assertNotEquals
  3. assertTrue
  4. assertFalse
  5. assertNull
  6. assertNotNull

Assert.assertEquals(actual, expected):
This assertion is used to compare expected and actual values in selenium WebDriver. If both values are same then it will continue execution. But if fails then immediately it will mark the test method as fail and exit from that test method.

Sample Code:
public void assertCheck(){
WebDriver driver=new FirefoxDriver();
The above test will pass since both value matches.