Selenium Interview Questions & Answers

Posted On:January 18, 2019, Posted By: Latest Interview Questions, Views: 1465, Rating :

Best Selenium Interview Questions and Answers

Dear Readers, Welcome to Selenium Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your Job interview for the subject of Selenium. These Selenium Questions are very important for campus placement test and job interviews. As per my experience good interviewers hardly plan to ask any particular questions during your Job interview and these model questions are asked in the online technical test and interview of many IT companies.

1. What is Selenium?

Selenium is a robust test automation suite that is used for automating web based applications. It supports multiple browsers, programming languages and platforms.
Interview Questions on Selenium

2. What are different forms of selenium?

Selenium comes in four forms-
Selenium WebDriver - Selenium WebDriver is used to automate web applications using browser's native methods.
Selenium IDE - A firefox plugin that works on record and play back principle.
Selenium RC - Selenium Remote Control(RC) is officially deprecated by selenium and it used to work on javascript to automate the web applications.
Selenium Grid - Allows selenium tests to run in parallel across multiple machines.
 

3. What are some advantages of selenium?

Following are the advantages of selenium-
Selenium is open source and free to use without any licensing cost.
It supports multiple languages like Java, ruby, python etc.
It supports multi browser testing.
It has good amount of resources and helping community over the internet.
Using selenium IDE component, non-programmers can also write automation scripts
Using selenium grid component, distributed testing can be carried out on remote machines possible.
 

4. What are some limitations of selenium?

Following are the limitations of selenium-
We cannot test desktop application using selenium.
We cannot test web services using selenium.
For creating robust scripts in selenium webdriver, programming langauge knowledge is required.
We have to rely on external libraries and tools forperforming tasks like - logging(log4J), testing framework-(testNG, JUnit), reading from external files(POI for excels) etc.
 

5. Which all browsers are supported by selenium webdriver?

Some commonly used browsers supported by selenium are-
Google Chrome - ChromeDriver
Firefox - FireFoxDriver
Internet Explorer - InternetExplorerDriver
Safari - SafariDriver
HtmlUnit (Headless browser) - HtmlUnitDriver
Android - Selendroid/Appium
IOS - ios-driver/Appium
 

6. Can we test APIs or web services using selenium webdriver?

No selenium webdriver uses browser's native method to automate the web applications. Since web services are headless, so we cannot automate web services using selenium webdriver.
 

7. What are the testing type supported by Selenium WebDriver?

Selenium webdriver can be used for performing automated functional and regression testing.
 

8. What are various ways of locating an element in selenium?

The different locators in selenium are-
Id
XPath
cssSelector
className
tagName
name
linkText
partialLinkText
 

9. What is an XPath?

Xpath or XML path is a query language for selecting nodes from XML documents. XPath is one of the locators supported by selenium webdriver.
 

10. What is an absolute XPath?

An absolute XPath is a way of locating an element using an XML expression beginning from root node i.e. html node in case of web pages. The main disadvantage of absolute xpath is that even with slightest change in the UI or any element the whole absolute XPath fails.
Example - html/body/div/div[2]/div/div/div/div[1]/div/input
 

11. What is a relative XPath?

A relative XPath is a way of locating an element using an XML expression beginning from anywhere in the HTML document. There are different ways of creating relative XPaths which are used for creating robust XPaths (unaffected by changes in other UI elements).
Example - //input[@id='username']
 

12. What is the difference between single slash(/) and double slash(//) in XPath?

In XPath a single slash is used for creating XPaths with absolute paths beginning from root node.
Whereas double slash is used for creating relative XPaths.
 

13. How can we inspect the web element attributes in order to use them in different locators?

Using Firebug or developer tools we can inspect the specific web elements.
Firebug is a plugin of firefox that provides various development tools for debugging applications. From automation perspective, firebug is used specifically for inspecting web-elements in order to use their attributes like id, class, name etc. in different locators.
 

14. How can we locate an element by only partially matching its attributes value in Xpath?

Using contains() method we can locate an element by partially matching its attribute's value. This is particularly helpful in the scenarios where the attributes have dynamic values with certain constant part.
xPath expression = //*[contains(@name,'user')]
The above statement will match the all the values of name attribute containing the word 'user' in them.
 

15. How can we locate elements using their text in XPath?

Using the text() method -
xPathExpression = //*[text()='username']
 

16. How can we move to parent of an element using XPath?

Using '..' expression in XPath we can move to parent of an element.
 

17. How can we move to nth child element using XPath?

There are two ways of navigating to the nth element using XPath-
Using square brackets with index position-
Example - div[2] will find the second div element.
Using position()-
Example - div[position()=3] will find the third div element.
 

18. What is the syntax of finding elements by class using CSS Selector?

By .className we can select all the element belonging to a particluar class e.g. '.red' will select all elements having class 'red'.
 

19. What is the syntax of finding elements by id using CSS Selector?

By #idValue we can select all the element belonging to a particluar class e.g. '#userId' will select the element having id - userId.
 

20. How can we select elements by their attribute value using CSS Selector?

Using [attribute=value] we can select all the element belonging to a particluar class e.g. '[type=small]' will select the element having attribute type of value 'small'.
 

21. How can we move to nth child element using css selector?

Using :nth-child(n) we can move to the nth child element e.g. div:nth-child(2) will locate 2nd div element of its parent.
 

22. What is fundamental difference between XPath and css selector?

The fundamental difference between XPath and css selector is using XPaths we traverse up in the document i.e. we can move to parent elements. Whereas using CSS selector we can only move downwards in the document.
 

23. How can we launch different browsers in selenium webdriver?

By creating an instance of driver of a particular browser-
WebDriver driver = new FirefoxDriver();

 

24. What is the use of driver.get("URL") and driver.navigate().to("URL") command? Is there any difference between the two?

Both driver.get("URL") and driver.navigate().to("URL") commands are used to navigate to a URL passed as parameter. 
There is no difference between the two commands.
 

25. How can we type text in a textbox element using selenium?

Using sendKeys() method we can type text in a textbox-
WebElement searchTextBox = driver.findElement(By.id("search"));
searchTextBox.sendKeys("searchTerm");
 

26. How can we clear a text written in a textbox?

Using clear() method we can delete the text written in a textbox.
driver.findElement(By.id("elementLocator")).clear();
 

27. How to check a checkBox in selenium?

The same click() method used for clicking buttons or radio buttons can be used for checking checkbox as well.
 

28. How can we submit a form in selenium?

Using submit() method we can submit a form in selenium.
driver.findElement(By.id("form1")).submit();
Also, the click() method can be used for the same purpose.

 

29. Explain the difference between close and quit command.

driver.close() - Used to close the current browser having focus
driver.quit() - Used to close all the browser instances
 

30. How to switch between multiple windows in selenium?

Selenium has driver.getWindowHandles() and driver.switchTo().window("{windowHandleName}") commands to work with multiple windows. The getWindowHandles() command returns a list of ids corresponding to each window and on passing a particular window handle to driver.switchTo().window("{windowHandleName}") command we can switch control/focus to that particular window.
 
for (String windowHandle : driver.getWindowHandles()) {
     driver.switchTo().window(handle);
}
 

31. What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in selenium?

driver.getWindowHandle() returns a handle of the current page (a unique identifier)
Whereas driver.getWindowHandles() returns a set of handles of the all the pages available.

 

32. How can we move to a particular frame in selenium?

The driver.switchTo() commands can be used for switching to frames.
driver.switchTo().frame("{frameIndex/frameId/frameName}");
For locating a frame we can either use the index (starting from 0), its name or Id.

 

33. Can we move back and forward in browser using selenium?

Yes, using driver.navigate().back() and driver.navigate().forward() commands we can move backward and forward in a browser.
 

34. Is there a way to refresh browser using selenium?

There a multiple ways to refresh a page in selenium-
Using driver.navigate().refresh() command
Using sendKeys(Keys.F5) on any textbox on the webpage
Using driver.get("URL") on the current URL or using driver.getCurrentUrl()
Using driver.navigate().to("URL") on the current URL or driver.navigate().to(driver.getCurrentUrl());

 

35. How can we maximize browser window in selenium?

We can maximize browser window in selenium using following command-
driver.manage().window().maximize();

 

36. How can we fetch a text written over an element?

Using getText() method we can fetch the text over an element.
String text = driver.findElement("elementLocator").getText();
 

37. How can we find the value of different attributes like name, class, value of an element?

Using getAttribute("{attributeName}") method we can find the value of different attrbutes of an element e.g.-
String valueAttribute =
driver.findElement(By.id("elementLocator")).getAttribute("value");

 

38. How to delete cookies in selenium?

Using deleteAllCookies() method-
driver.manage().deleteAllCookies();
 

39. What is an implicit wait in selenium?

An implicit wait is a type of wait which waits for a specified time while locating an element before throwing NoSuchElementException. As by default selenium tries to find elements immediately when required without any wait. So, it is good to use implicit wait. This wait is applied to all the elements of the current driver instance.
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
 

40. What is an explicit wait in selenium?

An explicit wait is a type of wait which is applied to a particular web element untill the expected condition specified is met.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("elementId")));
 

41. What are some expected conditions that can be used in Explicit waits?

Some of the commonly used expected conditions of an element that can be used with expicit waits are-
elementToBeClickable(WebElement element or By locator)
stalenessOf(WebElement element)
visibilityOf(WebElement element)
visibilityOfElementLocated(By locator)
invisibilityOfElementLocated(By locator)
attributeContains(WebElement element, String attribute, String value)
alertIsPresent()
titleContains(String title)
titleIs(String title)
textToBePresentInElementLocated(By, String)

 

42. What is fluent wait in selenium?

A fluent wait is a type of wait in which we can also specify polling interval(intervals after which driver will try to find the element) along with the maximum timeout value.
Wait wait = new FluentWait(driver)
     .withTimeout(20, SECONDS)
     .pollingEvery(5, SECONDS)
     .ignoring(NoSuchElementException.class);
   WebElement textBox = wait.until(new Function<webdriver,webElement>() {
     public WebElement apply(WebDriver driver) {
     return driver.findElement(By.id("textBoxId"));
     }
}
);
 

43. What are the different keyboard operations that can be performed in selenium?

The different keyboard operations that can be performed in selenium are-
.sendKeys("sequence of characters") - Used for passing charcter sequesnce to an input or textbox element.
.pressKey("non-text keys") - Used for keys like control, function keys etc that ae non text.
.releaseKey("non-text keys") - Used in conjuntion with keypress event to simulate releasing a key from keyboard event.
 

44. What are the different mouse actions that can be performed?

The different mouse evenets supported in selenium are
click(WebElement element)
doubleClick(WebElement element)
contextClick(WebElement element)
mouseDown(WebElement element)
mouseUp(WebElement element)
mouseMove(WebElement element)
mouseMove(WebElement element, long xOffset, long yOffset)

 

45. Write the code to double click an element in selenium?

Code to double click an element in selenium-
Actions action = new Actions(driver);
WebElement element=driver.findElement(By.id("elementId"));
action.doubleClick(element).perform();
 

46. Write the code to right click an element in selenium?

Code to right click an element in selenium-
Actions action = new Actions(driver);
WebElement element=driver.findElement(By.id("elementId"));
action.contextClick(element).perform();
 

47. How to mouse hover an element in selenium?

Code to mouse hover over an element in selenium-
Actions action = new Actions(driver);
WebElement element=driver.findElement(By.id("elementId"));
action.moveToElement(element).perform();
 

48. How to fetch the current page URL in selenium?

Using getCurrentURL() command we can fetch the current page URL-
driver.getCurrentUrl();
 

49. How can we fetch title of the page in selenium?

Using driver.getTitle(); we can fetch the page title in selenium. This method returns a string containing the title of the webpage.

 

50. How can we fetch the page source in selenium?

Using driver.getPageSource(); we can fetch the page source in selenium. This method returns a string containing the page source.

 

51. How to verify tooltip text using selenium?

 
Tooltips webelements have an attribute of type 'title'. By fetching the value of 'title' attribute we can verify the tooltip text in selenium.
 
String toolTipText = element.getAttribute("title");

 

52. How to locate a link using its text in selenium?

 
Using linkText() and partialLinkText() we can locate a link. The difference between the two is linkText matches the complete string passed as parameter to the link texts. Whereas partialLinkText matches the string parameter partially with the link texts.
 
WebElement link1 = driver.findElement(By.linkText(“artOfTesting”));
WebElement link2 = driver.findElement(By.partialLinkText(“artOf”));
 

53. What are DesiredCapabilities in selenium webdriver?

 
Desired capabilities are a set of key-value pairs that are used for storing or configuring browser specific properties like its version, platform etc in the browser instances.
 
 

54. How can we find all the links on a web page?

 
All the links are of anchor tag 'a'. So by locating elements of tagName 'a' we can find all the links on a webpage.
 
List<WebElement> links = driver.findElements(By.tagName("a"));

 

55. What are some commonly encountered exceptions in selenium?

 
Some of the commonly seen exception in selenium are-
 
NoSuchElementException - When no element could be located from the locator provided.
ElementNotVisibleException - When element is present in the dom but is not visible.
NoAlertPresentException - When we try to switch to an alert but the targetted alert is not present.
NoSuchFrameException - When we try to switch to a frame but the targetted frame is not present.
NoSuchWindowException - When we try to switch to a window but the targetted window is not present.
UnexpectedAlertPresentException - When an unexpected alert blocks normal interaction of the driver.
TimeoutException - When a command execution gets timeout.
InvalidElementStateException - When the state of an element is not appropriate for the desired action.
NoSuchAttributeException - When we are trying to fetch an attribute's value but the attribute is not correct
WebDriverException - When there is some issue with driver instance preventing it from getting launched.
 

56. How can we capture screenshots in selenium?

Using getScreenshotAs method of TakesScreenshot interface we can take the screenshots in selenium.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));
 

57. How to handle dropdowns in selenium?

Using Select class-
Select countriesDropDown = new Select(driver.findElement(By.id("countries")));
dropdown.selectByVisibleText("India");
//or using index of the option starting from 0
dropdown.selectByIndex(1);
//or using its value attribute
dropdown.selectByValue("Ind");
 

58. How to check which option in the dropdown is selected?

Using isSelected() method we can check the state of a dropdown's option.
Select countriesDropDown = new Select(driver.findElement(By.id("countries")));
dropdown.selectByVisibleText("India");
//returns true or false value
System.out.println(driver.findElement(By.id("India")).isSelected());
 

59. How can we check if an element is getting displayed on a web page?

Using isDisplayed method we can check if an element is getting displayed on a web page.
driver.findElement(By locator).isDisplayed();
 

60. How can we check if an element is enabled for interaction on a web page?

Using isEnabled method we can check if an element is enabled or not.
driver.findElement(By locator).isEnabled();

 

61. What is the difference between driver.findElement() and driver.findElements() commands?

The difference between driver.findElement() and driver.findElements() commands is- findElement() returns a single WebElement (found first) based on the locator passed as parameter. Whereas findElements() returns a list of WebElements, all satisfying the locator value passed.
Syntax of findElement()-
WebElement textbox = driver.findElement(By.id("textBoxLocator"));
Syntax of findElements()-
List <WebElement> elements = element.findElements(By.id(“value”));
Another difference between the two is- if no element is found then findElement() throws NoSuchElementException whereas findElements() returns a list of 0 elements.

 

62. Explain the difference between implicit wait and explicit wait.?

An implicit wait, while finding an element waits for a specified time before throwing NoSuchElementException in case element is not found. The timeout value remains valid throughout the webDriver's instance and for all the elements.
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
Whereas, Explicit wait is applied to a specified element only-
WebDriverWait wait = new WebDriverWait(driver, 5);  
wait.until(ExpectedConditions.presenceOfElementLocated(ElementLocator));
It is advisable to use explicit waits over implicit waits because higher timeout value of implicit wait set due to an element that takes time to be visible gets applied to all the elements. Thus increasing overall execution time of the script. On the other hand, we can apply different timeouts to different element in case of explicit waits.

 

63. How can we handle window UI elements and window POP ups using selenium?

Selenium is used for automating Web based application only(or browsers only). For handling window GUI elements we can use AutoIT. AutoIT is a freeware used for automating window GUI. The AutoIt scripts follow simple BASIC lanaguage like syntax and can be easily integrated with selenium tests.
 

64. What is Robot API?

Robot API is used for handling Keyboard or mouse events. It is generally used to upload files to the server in selenium automation.
Robot robot = new Robot();
//Simulate enter key action
robot.keyPress(KeyEvent.VK_ENTER);
 

65. How to do file upload in selenium?

File upload action can be performed in multiple ways-
Using element.sendKeys("path of file") on the webElement of input tag and type file i.e. the elements should be like - 
<input type="file" name="fileUpload">
Using Robot API.
Using AutoIT API.

 

66. How to handle HTTPS website in selenium? or How to accept the SSL untrusted connection?

Using profiles in firefox we can handle accept the SSL untrusted connection certificate. Profiles are basically set of user preferences stored in a file.
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true); 
profile.setAssumeUntrustedCertificateIssuer(false);
WebDriver driver = new FirefoxDriver(profile); 

 

67 How to do drag and drop in selenium?

Using Action class, drag and drop can be performed in selenium. Sample code-
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(SourceElement)
.moveToElement(TargetElement)
.release(TargetElement)
.build();
dragAndDrop.perform();
 

68. How to execute javascript in selenium?

JavaScript can be executed in selenium using JavaScriptExecuter. Sample code for javascript execution-
WebDriver driver = new FireFoxDriver();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("{JavaScript Code}");
}
 

69. How to handle alerts in selenium?

In order to accept or dismiss an alert box the alert class is used. This requires first switching to the alert box and than using accept() or dismiss() command as the case may be.
Alert alert = driver.switchTo().alert(); 
//To accept the alert
alert.accept();
 
Alert alert = driver.switchTo().alert(); 
//To cancel the alert box
alert.dismiss();
 

70. What is HtmlUnitDriver?

HtmlUnitDriver is the fastest WebDriver. Unlike other drivers (FireFoxDriver, ChromeDriver etc), the HtmlUnitDriver is non-GUI, while running no browser gets launched.

 

71. How to handle hidden elements in Selenium webDriver?

Using javaScript executor we can handle hidden elements-
(JavascriptExecutor(driver)) .executeScript("document.getElementsByClassName(ElementLocator).click();");
 

72. What is Page Object Model or POM?

Page Object Model(POM) is a design pattern in selenium. A design pattern is a solution or a set of standards that are used for solving commonly occuring software problems.
Now coming to POM - POM helps to create a framework for maintaining selenium scripts. In POM for each page of the application a class is created having the web elements belonging to the page and methods handling the events in that page. The test scripts are maintained in seperate files and the methods of the page object files are called from the test scripts file.
 

73. What are the advantages of POM?

The advantages are POM are-
Using POM we can create an Object Repository, a set of web elements in seperate files along with their associated functions. Thereby keeping code clean.
For any chnage in UI(or web elements) only page object files are required to be updated leaving test files unchanged.
It makes code reusable and maintable.
 

74. What is Page Factory?

Page factory is an implementation of Page Object Model in selenium. It provides @FindBy annotation to find web elements and PageFactory.initElements() method to initialize all web elements defined with @FindBy annotation.
public class SamplePage {
    WebDriver driver;
    @FindBy(id="search")
    WebElement searchTextBox;
    @FindBy(name="searchBtn")
    WebElement searchButton;
    //Constructor
    public samplePage(WebDriver driver){
        this.driver = driver;
        //initElements method to initialize all elements
        PageFactory.initElements(driver, this);
    }
    //Sample method
    public void search(String searchTerm){
        searchTextBox.sendKeys(searchTerm);  
        searchButton.click();
    }
}
 

75. What is an Object repository?

An object repository is centralized location of all the object or WebElements of the test scripts. In selenium we can create object repository using Page Object Model and Page Factory design patterns.
 

76. What is a data driven framework?

A data driven framework is one in which the test data is put in external files like csv, excel etc separated from test logic written in test script files. The test data drives the test cases, i.e. the test methods run for each set of test data values. TestNG provides inherent support for data driven testing using @dataProvider annotation.
 

77. What is a keyword driven framework?

A keyword driven framework is one in which the actions are associated with keywords and kept in external files e.g. an action of launching a browser will be associated with keyword - launchBrowser(), action to write in a textbox with keyword - writeInTextBox(webElement, textToWrite) etc. The code to perform the action based on a keyword specified in external file is implemented in the framework itself. 
In this way the test steps can be written in a file by even a person of non-programming background once all the identified actions are implemented.
 

78. What is a hybrid framework?

A hybrid framework is a combination of one or more frameworks. Normally it is associated with combination of data driven and keyword driven frameworks where both the test data and test actions are kept in external files(in the form of table).
 

79. What is selenium Grid?

Selenium grid is a tool that helps in distributed running of test scripts across different machines having different browsers, browser version, platforms etc in parallel. In selenium grid there is hub that is a central server managing all the distributed machines known as nodes.
 

80. What are some advantages of selenium grid?

The advantages of selenium grid are-
It allows running test cases in parallel thereby saving test execution time.
Multi browser testing is possible using selenium grid by running the test on machines having different browsers.
It is allows multi-platform testing by configuring nodes having different operating systems.
 

81. What is a hub in selenium grid?

A hub is server or a central point in selenium grid that controls the test executions on the different machines.
 

82. What is a node in selenium grid?

Nodes are the machines which are attached to the selenium grid hub and have selenium instances running the test scripts. Unlike hub there can be multiple nodes in selenium grid.
 

83. Explain the line of code Webdriver driver = new FirefoxDriver();.

In the line of code Webdriver driver = new FirefoxDriver(); 'WebDriver' is an interface and we are creating an object of type WebDriver instantiating an object of FirefoxDriver class.
 

84 What is the purpose of creating a reference variable- 'driver' of type WebDriver instead of directly creating a FireFoxDriver object or any other driver's reference in the statement Webdriver driver = new FirefoxDriver();?

 
By creating a reference variable of type WebDriver we can use the same variable to work with multiple browsers like ChromeDriver, IEDriver etc.
 

85. What is testNG?

TestNG(NG for Next Generation) is a testing framework that can be integrated with selenium or any other automation tool to provide multiple capabilities like assertions, reporting, parallel test execution etc.
 

86. What are some advantages of testNG?

Following are the advantages of testNG-
TestNG provides different assertions that helps in checking the expected and actual results.
It provides parallel execution of test methods.
We can define dependency of one test method over other in TestNG.
We can assign priority to test methods in selenium.
It allows grouping of test methods into test groups.
It allows data driven testing using @DataProvider annotation.
It has inherent support for reporting.
It has support for parameterizing test cases using @Parameters annotation.

 

87. What is the use of testng.xml file?

testng.xml file is used for configuring the whole test suite. In testng.xml file we can create test suite, create test groups, mark tests for parallel execution, add listeners and pass parameters to test scripts. Later this testng.xml file can be used for triggering the test suite.
 

88. How can we pass parameter to test script using testNG?

Using @Parameter annotaion and 'parameter' tag in testng.xml we can pass paramters to test scripts.
Sample testng.xml -
<suite name="sampleTestSuite">
   <test name="sampleTest">   
      <parameter name="sampleParamName" value="sampleParamValue"/>
      <classes>
         <class name="TestFile" />
      </classes>      
   </test>
</suite>
 
Sample test script-
public class TestFile {
   @Test
   @Parameters("sampleParamName")
   public void parameterTest(String paramValue) {
      System.out.println("Value of sampleParamName is - " + sampleParamName);
   }
 

89. How can we create data driven framework using testNG?

Using @DataProvider we can create a data driven framework in which data is passed to the associated test method and multiple iteration of the test runs for the different test data values passed from the @DataProvider method. The method annotated with @DataProvider annotation return a 2D array of object.
//Data provider returning 2D array of 3*2 matrix
 @DataProvider(name = "dataProvider1")
   public Object[][] dataProviderMethod1() {
      return new Object[][] {{"kuldeep","rana"}, {"k1","r1"},{"k2","r2"}};
   }
 
   //This method is bound to the above data provider returning 2D array of 3*2 matrix
   //The test case will run 3 times with different set of values
   @Test(dataProvider = "dataProvider1")
   public void sampleTest(String s1, String s2) {
      System.out.println(s1 + " " + s2);
   }
 

90. What is the use of @Listener annotation in TestNG?

TestNG provides us different kind of listeners using which we can perform some action in case an event has triggered. Usually testNG listeners are used for configuring reports and logging. One of the most widely used lisetner in testNG is ITestListener interface. It has methods like onTestSuccess, onTestFailure, onTestSkipped etc. We need to implement this interface creating a listner class of our own. After that using the @Listener annotation we can use specify that for a particular test class our customized listener class should be used.
@Listeners(PackageName.CustomizedListenerClassName.class)
public class TestClass {
    WebDriver driver= new FirefoxDriver();@Test
    public void testMethod(){
    //test logic
    }
}
 

91. What is the use of @Factory annotation in TestNG?

@Factory annotation helps in dynamic execution of test cases. Using @Factory annotation we can pass parameters to the whole test class at run time. The parameters passed can be used by one or more test methods of that class.
Example - there are two classes TestClass and the TestFactory class. Because of the @Factory annotation the test methods in class TestClass will run twice with the data "k1" and "k2"
public class TestClass{
    private String str;
 
    //Constructor
    public TestClass(String str) {
        this.str = str;
    }
 
    @Test
    public void TestMethod() {
        System.out.println(str);
    }
}
 
public class TestFactory{
    //The test methods in class TestClass will run twice with data "k1" and "k2"
    @Factory
    public Object[] factoryMethod() {
        return new Object[] { new TestClass("K1"), new TestClass("k2") };
    }
}

 

92. What is difference between @Factory and @DataProvider annotation?

@Factory method creates instances of test class and run all the test methods in that class with different set of data.
Whereas, @DataProvider is bound to individual test methods and run the specific methods multiple times.
 

93. How can we make one test method dependent on other using TestNG?

Using dependsOnMethods parameter inside @Test annotation in testNG we can make one test method run only after successful execution of dependent test method.
 @Test(dependsOnMethods = { "preTests" })

 

94. How can we set priority of test cases in TestNG?

Using priority parameter in @Test annotation in TestNG we can define priority of test cases. The default priority of test when not specified is integer value 0. Example-
@Test(priority=1)
 

95. What are commonly used TestNG annotations?

The commonly used TestNG annotations are-
@Test- @Test annotation marks a method as Test method.
@BeforeSuite- The annotated method will run only once before all tests in this suite have run.
@AfterSuite-The annotated method will run only once after all tests in this suite have run.
@BeforeClass-The annotated method will run only once before the first test method in the current class is invoked.
@AfterClass-The annotated method will run only once after all the test methods in the current class have been run.
@BeforeTest-The annotated method will run before any test method belonging to the classes inside the <test> tag is run.
@AfterTest-The annotated method will run after all the test methods belonging to the classes inside the <test> tag have run.
 

96. What are some common assertions provided by testNG?

Some of the common assertions provided by testNG are-
assertEquals(String actual, String expected, String message) - (and other overloaded data type in parameters)
assertNotEquals(double data1, double data2, String message) - (and other overloaded data type in parameters)
assertFalse(boolean condition, String message)
assertTrue(boolean condition, String message)
assertNotNull(Object object)
fail(boolean condition, String message)
true(String message)
 

97. How can we run test cases in parallel using TestNG?

In order to run the tests in parallel just add these two key value pairs in suite-
parallel="{methods/tests/classes}"
thread-count="{number of thread you want to run simultaneously}".
<suite name="ArtOfTestingTestSuite" parallel="methods" thread-count="5">
Check Running Selenium Tests in parallel for details.
 

98. Name an API used for reading and writing data to excel files.

Apache POI API and JXL(Java Excel API) can be used for reading, writing and updating excel files.
 

99. Name an API used for logging in Java.

Log4j is an open source API widely used for logging in Java. It supports multiple levels of logging like - ALL, DEBUG, INFO, WARN, ERROR, TRACE and FATAL.
 

100. What is the use of logging in automation?

Logging helps in debugging the tests when required and also provides a storage of test's runtime behaviour.