KEMBAR78
Selenium Interview Questions and Answers by Advanto | PDF | Selenium (Software) | X Path
0% found this document useful (0 votes)
87 views62 pages

Selenium Interview Questions and Answers by Advanto

Uploaded by

Sandip Pathak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views62 pages

Selenium Interview Questions and Answers by Advanto

Uploaded by

Sandip Pathak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Selenium Interview Questions and Answers

Q #1) What is Automation Testing?


Automation testing or Test Automation is a process of automating the manual process to test the application/system under test.
Automation testing involves the use of a separate testing tool which lets you create test scripts which can be executed repeatedly and
doesn’t require any manual intervention.

Q #2) What are the benefits of Automation Testing?


Benefits of Automation testing are:

1. Supports execution of repeated test cases


2. Aids in testing a large test matrix
3. Enables parallel execution
4. Encourages unattended execution
5. Improves accuracy thereby reducing human-generated errors
6. Saves time and money
Q #3) Why should Selenium be selected as a test tool?
Selenium

1. is a free and open source


2. have a large user base and helping communities
3. have cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
4. have great platform compatibility (Windows, Mac OS, Linux etc.)
5. supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
6. has fresh and regular repository developments
7. supports distributed testing
Q #4) What is Selenium? What are the different Selenium components?
Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation
testing of functional aspects of web-based applications and a wide range of browsers and platforms. Due to its existence in the open
source community, it has become one of the most accepted tools amongst the testing professionals.

Selenium is not just a single tool or a utility, rather a package of several testing tools and for the same reason, it is referred to as a Suite.
Each of these tools is designed to cater different testing and test environment requirements.

The suite package constitutes the following sets of tools:

 Selenium Integrated Development Environment (IDE) – Selenium IDE is a record and playback tool. It is distributed as a
Firefox Plugin.
 Selenium Remote Control (RC) – Selenium RC is a server that allows a user to create test scripts in the desired programming
language. It also allows executing test scripts within the large spectrum of browsers.
 Selenium WebDriver – WebDriver is a different tool altogether that has various advantages over Selenium RC. WebDriver
directly communicates with the web browser and uses its native compatibility to automate.
 Selenium Grid – Selenium Grid is used to distribute your test execution on multiple platforms and environments concurrently.
Q #5) What are the testing types that can be supported by Selenium?
Selenium supports the following types of testing:

1. Functional Testing
2. Regression Testing
Q #6) What are the limitations of Selenium?
Following are the limitations of Selenium:

 Selenium supports testing of only web-based applications


 Mobile applications cannot be tested using Selenium
 Captcha and Barcode readers cannot be tested using Selenium
 Reports can only be generated using third-party tools like TestNG or JUnit.
 As Selenium is a free tool, thus there is no ready vendor support through the user can find numerous helping communities.
 The user is expected to possess prior programming language knowledge.
Q #7) What is the difference between Selenium IDE, Selenium RC, and WebDriver?

Q #8) When should I use Selenium IDE?


Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its record and playback feature makes it
exceptionally easy to learn with minimal acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.

Q #9) What is Selenese?


Selenese is the language which is used to write test scripts in Selenium IDE.

Q #10) What are the different types of locators in Selenium?


The 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:
 ID
 ClassName
 Name
 TagName
 LinkText
 PartialLinkText
 Xpath
 CSS Selector
 DOM
Q #11) What is the difference between assert and verify commands?
Assert: Assert command checks whether the given condition is true or false. Let’s say we assert whether the given element is present on
the web page or not. If the condition is true then the program control will execute the next test step but if the condition is false, the
execution would stop and no further test would be executed.
Verify: Verify command also checks whether the given condition is true or false. Irrespective of the condition being true or false, the
program execution doesn’t halt i.e. any failure during verification would not stop the execution and all the test steps would be executed.
Q #12) What is an XPath?
XPath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store,
organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being markup
languages and since they fall under the same umbrella, XPath can be used to locate HTML elements.
The fundamental behind locating elements using XPath is the traversing between various elements across the entire page and thus
enabling a user to find an element with the reference of another element.

Q #13) What is the difference between “/” and “//” in Xpath?


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.
Q #14) What is Same origin policy and how it can be handled?
The problem of same origin policy disallows to access the DOM of a document from an origin that is different from the origin we are trying
to access the document.

Origin is a sequential combination of scheme, host, and port of the URL. For example, for a URL
https://www.softwaretestinghelp.com/resources/, the origin is a combination of http, softwaretestinghelp.com, 80 correspondingly.

Thus the Selenium Core (JavaScript Program) cannot access the elements from an origin that is different from where it was launched.
For Example, if I have launched the JavaScript Program from “https://www.softwaretestinghelp.com”, then I would be able to access the
pages within the same domain such as “https://www.softwaretestinghelp.com/resources” or “https://www.softwaretestinghelp.com/istqb-
free-updates/”. The other domains like google.com, seleniumhq.org would no more be accessible.

So, In order to handle the same origin policy, Selenium Remote Control was introduced.
Q #15) When should I use Selenium Grid?
Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve
distributed test execution, testing under different environments and saving execution time remarkably.
Q #16) What do we mean by Selenium 1 and Selenium 2?
Selenium RC and WebDriver, in a combination, are popularly known as Selenium 2. Selenium RC alone is also referred to as Selenium
1.
Q #17) Which is the latest Selenium tool?
WebDriver

Q #18) How do I launch the browser using WebDriver?


The following syntax can be used to launch Browser:
WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();
Q #19) What are the different types of Drivers available in WebDriver?
The different drivers available in WebDriver are:

 FirefoxDriver
 InternetExplorerDriver
 ChromeDriver
 SafariDriver
 OperaDriver
 AndroidDriver
 IPhoneDriver
 HtmlUnitDriver
Q #20) What are the different types of waits available in WebDriver?
There are two types of waits available in WebDriver:
1. Implicit Wait
2. Explicit Wait
Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command
across the entire test script. Thus, the subsequent test step would only execute when the 30 seconds have elapsed after executing the
previous test step/command.
Explicit Wait: Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed.
Unlike Implicit waits, explicit waits are applied for a particular instance only.
Q #21) How to type in a textbox using Selenium?
The user can use sendKeys(“String to be entered”) to enter the string in the textbox.

Syntax:
WebElement username = drv.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);
Q #22) How can you find if an element in displayed on the screen?
WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons,
drop boxes, checkboxes, radio buttons, labels etc.

1. isDisplayed()
2. isSelected()
3. isEnabled()
Syntax:
isDisplayed():
boolean buttonPresence = driver.findElement(By.id(“gbqfba”)).isDisplayed();
isSelected():
boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isSelected();
isEnabled():
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();
Q #23) How can we get a text of a web element?
Get 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. It is also one of the extensively used commands for verification of messages, labels, errors etc displayed on the web pages.

Syntax:
String Text = driver.findElement(By.id(“Text”)).getText();
Q #24) How to select value in a dropdown?
The value in the dropdown can be selected using WebDriver’s Select class.

Syntax:
selectByValue:
Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);
selectByVisibleText:
Select selectByVisibleText = new Select (driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);
selectByIndex:
Select selectByIndex = new Select(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);
Q #25) What are the different types of navigation commands?
Following are the navigation commands:
navigate().back() – The above command requires no parameters and takes back the user to the previous webpage in the web browser’s
history.
Sample code:
driver.navigate().back();
navigate().forward() – This command lets the user to navigate to the next web page with reference to the browser’s history.
Sample code:
driver.navigate().forward();
navigate().refresh() – This command lets the user to refresh the current web page there by reloading all the web elements.
Sample code:
driver.navigate().refresh();
navigate().to() – This command lets the user to launch a new web browser window and navigate to the specified URL.
Sample code:
driver.navigate().to(“https://google.com”);
Q #26) How to click on a hyper link using linkText?
driver.findElement(By.linkText(“Google”)).click();
The command finds the element using link text and then click on that element and thus the user would be re-directed to the
corresponding page.

The above-mentioned link can also be accessed by using the following command.

driver.findElement(By.partialLinkText(“Goo”)).click();
The above command finds the element based on the substring of the link provided in the parenthesis and thus partialLinkText() finds the
web element with the specified substring and then clicks on it.

Q #27) How to handle frame in WebDriver?


An inline frame acronym as iframe is used to insert another document within the current HTML document or simply a web page into a
web page by enabling nesting.

Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
Locating iframe using index
frame(index)
driver.switchTo().frame(0);
frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();
Q #28) When do we use findElement() and findElements()?
findElement(): findElement() is used to find the first element in the current web page matching to the specified locator value. Take a note
that only first matching element would be fetched.
Syntax:
WebElement element = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web page matching to the specified locator value. Take a
note that all the matching elements would be fetched and stored in the list of WebElements.
Syntax:
List <WebElement> elementList = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
Q #29) How to find more than one web element in the list?
At times, we may come across elements of the same type like multiple hyperlinks, images etc arranged in an ordered or unordered list.
Thus, it makes absolute sense to deal with such elements by a single piece of code and this can be done using WebElement List.

Q #30) What is the difference between driver.close() and driver.quit command?


close(): WebDriver’s close() method closes the web browser window that the user is currently working on or we can also say the window
that is being currently accessed by the WebDriver. The command neither requires any parameter nor does it return any value.
quit(): Unlike close() method, quit() method closes down all the windows that the program has opened. Same as close() method, the
command neither requires any parameter nor does is return any value.
Q #31) Can Selenium handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing. Therefore, windows pop up cannot be handled using
Selenium.

Suggested Reading => Java Architect Interview Questions


Q #32) How can we handle web-based pop-up?
WebDriver offers the users a very efficient way to handle these pop-ups using Alert interface. There are the four methods that we would
be using along with the Alert interface.
 void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop-up window appears.
 void accept() – The accept() method clicks on the “Ok” button as soon as the pop-up window appears.
 String getText() – The getText() method returns the text displayed on the alert box.
 void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
Syntax:
// accepting javascript alert
Alert alert = driver.switchTo().alert();
alert.accept();
Q #33) How can we handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support testing of windows
based applications. However Selenium alone can’t help the situation but along with some third-party intervention, this problem can be
overcome. There are several third-party tools available for handling window based pop-ups along with the selenium like AutoIT, Robot
class etc.

Q #34) How to assert the title of the web page?


//verify the title of the web page
assertTrue(“The title of the window is incorrect.”,driver.getTitle().equals(“Title of the page”));
Q #35) How to mouse hover on a web element using WebDriver?
WebDriver offers a wide range of interaction utilities that the user can exploit to automate mouse and keyboard events. Action Interface is
one such utility which simulates the single user interactions.

Thus, In the following scenario, we have used Action Interface to mouse hover on a drop down which then opens a list of options.

Sample Code:
// Instantiating Action Interface
Actions actions=new Actions(driver);
// howering on the dropdown
actions.moveToElement(driver.findElement(By.id("id of the dropdown"))).perform();
// Clicking on one of the items in the list options
WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));
subLinkOption.click();
Q #36) How to retrieve CSS properties of an element?
The values of the css properties can be retrieved using a get() method:

Syntax:
driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”);
Q #37) How to capture screenshot in WebDriver?
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class CaptureScreenshot {


WebDriver driver;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.get("https://google.com");
}
@After
public void tearDown() throws Exception {
driver.quit();
}

@Test
public void test() throws IOException {
// Code to capture the screenshot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Code to copy the screenshot in the desired location
FileUtils.copyFile(scrFile, new File("C:\\CaptureScreenshot\\google.jpg"))
}
}
Q #38) What is Junit?
Junit is a unit testing framework introduced by Apache. Junit is based on Java.
Q #39) What are Junit annotations?
Following are the JUnit Annotations:

 @Test: Annotation lets the system know that the method annotated as @Test is a test method. There can be multiple test
methods in a single test script.
 @Before: Method annotated as @Before lets the system know that this method shall be executed every time before each of the
test methods.
 @After: Method annotated as @After lets the system know that this method shall be executed every time after each of the test
method.
 @BeforeClass: Method annotated as @BeforeClass lets the system know that this method shall be executed once before any of
the test methods.
 @AfterClass: Method annotated as @AfterClass lets the system know that this method shall be executed once after any of the
test methods.
 @Ignore: Method annotated as @Ignore lets the system know that this method shall not be executed.
Q #40) What is TestNG and how is it better than Junit?
TestNG is an advanced framework designed in a way to leverage the benefits by both the developers and testers. With the
commencement of the frameworks, JUnit gained enormous popularity across the Java applications, Java developers and Java testers
with remarkably increasing the code quality. Despite being easy to use and straightforward, JUnit has its own limitations which give rise
to the need of bringing TestNG into the picture. TestNG is an open source framework which is distributed under the Apache Software
License and is readily available for download.
TestNG with WebDriver provides an efficient and effective test result format that can, in turn, be shared with the stakeholders to have a
glimpse on the product’s/application’s health thereby eliminating the drawback of WebDriver’s incapability to generate test reports.
TestNG has an inbuilt exception handling mechanism which lets the program to run without terminating unexpectedly.
There are various advantages that make TestNG superior to JUnit. Some of them are:

 Added advance and easy annotations


 Execution patterns can set
 Concurrent execution of test scripts
 Test case dependencies can be set
Q #41) How to set test case priority in TestNG?
Setting Priority in TestNG
Code Snippet
package TestNG;
import org.testng.annotations.*;
public class SettingPriority {
@Test(priority=0)
public void method1() {
}
@Test(priority=1)
public void method2() {
}
@Test(priority=2)
public void method3() {
}
}
Test Execution Sequence:
1. Method1
2. Method2
3. Method3
Q #42) What is a framework?
The framework is a constructive blend of various guidelines, coding standards, concepts, processes, practices, project hierarchies,
modularity, reporting mechanism, test data injections etc. to pillar automation testing.

Q #43) What are the advantages of the Automation framework?


The advantage of Test Automation framework
 Reusability of code
 Maximum coverage
 Recovery scenario
 Low-cost maintenance
 Minimal manual intervention
 Easy Reporting
Q #44) What are the different types of frameworks?
Below are the different types of frameworks:
1. Module Based Testing Framework: The framework divides the entire “Application Under Test” into the number of logical and
isolated modules. For each module, we create a separate and independent test script. Thus, when these test scripts have taken
together builds a larger test script representing more than one module.
2. Library Architecture Testing Framework: The basic fundamental behind the framework is to determine the common steps and
group them into functions under a library and call those functions in the test scripts whenever required.
3. Data Driven Testing Framework: Data Driven Testing Framework helps the user segregate the test script logic and the test data
from each other. It lets the user store the test data into an external database. The data is conventionally stored in “Key-Value”
pairs. Thus, the key can be used to access and populate the data within the test scripts.
4. Keyword Driven Testing Framework: The Keyword Driven testing framework is an extension to Data-driven Testing Framework
in a sense that it not only segregates the test data from the scripts, it also keeps the certain set of code belonging to the test script
into an external data file.
5. Hybrid Testing Framework: Hybrid Testing Framework is a combination of more than one above mentioned frameworks. The
best thing about such a setup is that it leverages the benefits of all kinds of associated frameworks.
6. Behavior Driven Development Framework: Behavior Driven Development framework allows automation of functional
validations in an easily readable and understandable format to Business Analysts, Developers, Testers, etc.
Q #45) How can I read test data from excels?
Test data can efficiently be read from excel using JXL or POI API. See detailed tutorial here.

Q #47) What is the difference between Selenium and QTP?


Feature Selenium Quick Test Professional (QTP)

Browser Selenium supports almost all the popular QTP supports Internet Explorer, Firefox and
Compatibility browsers like Firefox, Chrome, Safari, Internet Chrome. QTP only supports Windows
Explorer, Opera etc Operating System

Distribution Selenium is distributed as an open source tool QTP is distributed as a licensed tool and is
and is freely available commercialized

Application Selenium supports testing of only web based QTP supports testing of both the web based
under Test applications application and windows based application

Object Object Repository needs to be created as a QTP automatically creates and maintains
Repository separate entity Object Repository

Language Selenium supports multiple programming QTP supports only VB Script


Support languages like Java, C#, Ruby, Python, Perl
etc

Vendor Support As Selenium is a free tool, user would not get Users can easily get the vendor’s support in
the vendor’s support in troubleshooting issues case of any issue
Q #48) Can WebDriver test Mobile applications?
WebDriver cannot test Mobile applications. WebDriver is a web-based testing tool, therefore applications on the mobile browsers can be
tested.

Q #49) Can captcha be automated?


No, captcha and barcode reader cannot be automated.

Q #50) What is Object Repository? How can we create an Object Repository in Selenium?
Object Repository is a term used to refer to the collection of web elements belonging to Application Under Test (AUT) along with their
locator values. Thus, whenever the element is required within the script, the locator value can be populated from the Object Repository.
Object Repository is used to store locators in a centralized location instead of hardcoding them within the scripts.

In Selenium, objects can be stored in an excel sheet which can be populated inside the script whenever required.

That’s all for now.

Hope in this article you will find answers to most frequently asked Selenium and WebDriver Interview questions. The answers provided
here are also helpful for understanding the Selenium basics and advanced WebDriver topics.
1. What is Automation Testing?
Automation testing is the process of testing a software or application using an automation testing tool to find the
defects. In this process, executing the test scripts and generating the results are performed automatically by automation
tools. It is required when we have a huge amount of regression test cases. Some most popular tools to do automation
testing are HP QTP/UFT, Selenium WebDriver, etc.,

2. What are the benefits of Automation Testing?


This is one of the common interview questions in any Automation testing job.

1. Saves time and money. Automation testing is faster in execution.


2. Reusability of code. Create one time and execute multiple times with less or no maintenance.
3. Easy reporting. It generates automatic reports after test execution.
4. Easy for compatibility testing. It enables parallel execution in the combination of different OS and browser
environments.
5. Low-cost maintenance. It is cheaper compared to manual testing in a long run.
6. Automated testing is more reliable.
7. Automated testing is more powerful and versatile. Automation tools allow us to integrate with Cross Browser
Testing Tools, Jenkins, Github, etc.,
8. It is mostly used for regression testing. Supports execution of repeated test cases.
9. Minimal manual intervention. Test scripts can be run unattended.
10.Maximum coverage. It helps to increase the test coverage.

3. What are the challenges and limitations of Selenium WebDriver?


As we all know Selenium WebDriver is a tool that automates the browser to mimic real user actions on the web. Selenium
is a free open source testing tool. Some of the challenges with Selenium WebDriver are as follows

1. We cannot test the windows application


2. We cannot test mobile apps
3. Limited reporting
4. Handling dynamic Elements
5. Handling page load
6. Handling pop up windows
7. Handling captcha

Read the detailed explanation on the challenges and limitations of Selenium WebDriver

4. What type of tests have you automated?


Our main focus is to automate test cases to do Regression testing, Smoke & Sanity testing. Sometimes based on the
project and the test time estimation, we do focus on End to End testing.

5. How many test cases you have automated per day?


It is one of the Selenium Tricky Interview Questions.

Actually, it depends on Test case scenario complexity and length. I did automate 2-5 test scenarios per day when the
complexity is limited. Sometimes just 1 or fewer test scenarios in a day when the complexity is high.

6. What is a Framework?
A framework defines a set of rules or best practices that we can follow in a systematic way to achieve the desired results.
There are different types of automation frameworks and the most common ones are:

 Data-Driven Testing Framework


 Keyword Driven Testing Framework
 Hybrid Testing Framework
 Behavioural Driven Framework

Detailed Explanation: Types of Framework


7. What type of test cases to be automated?
Types of Test Cases To Automate are

 Data-driven test cases


 Test cases with higher complexity
 Test case with many database updates
 The test execution rate is high
 Smoke/Critical tests
 Tests with several combinations
 Graph test cases
 Higher manual execution time

Read in detail explanation on types of test cases to be automated here

8. What type of test cases not to be automated?


Types of Test Cases Not To Be Automated are

 Subjective Validation
 New Functionalities
 Strategic Development
 User Experience
 Complex Functionality
 Quality Control
 Low return on investment
 Installation and setup testing

Read in detail explanation on types of test cases not to be automated here

9. What are the advantages of the Test Automation Framework?


1. Reusability of code.
2. Easy reporting.
3. Low-cost maintenance.
4. Maximum Coverage
5. Minimal manual intervention

10. Have you created any Framework?


If you are a beginner: You can say “No, I didn’t get a chance to create a framework from the scratch. I have used the
framework which is already available. My contribution is mostly in creating test cases by using the existing framework.”

If you are a beginner but have good knowledge of creating framework: You can say “Yes, I have involved in
developing framework along with other automation testers in my company.”

If you are an experienced tester: You can say “I have contributed to developing framework.” or You can say “Yes, I have
created a framework from the scratch. There was no automation process in my previous company. I designed the
framework from the scratch.”

11. How would you explain the Selenium test automation framework in the
interview?
Here we have clearly explained each component of the Framework. Check this post to learn more about how to explain
the selenium test automation framework to the interviewer.

12. Why do you prefer Selenium Automation Tool?


I prefer Selenium Automation Tool because some of the benefits of Selenium to do automation testing are

 Free and open source – It is a free open source tool. There is no need to allot budget for this tool
 Help – Have large user base and helping communities.
 Cross-browser compatibility – It works on almost all popular browsers such as Chrome, Firefox, Internet Explorer,
and Safari.
 Cross Platform compatibility – It works on platforms such as Windows, Linux, Mac.
 Multiple programming languages – It supports programming languages such as Java, Phyton, Perl, Php, C#,
Ruby, etc.,
 Parallel Execution – Selenium Grid supports parallel execution of Selenium Scripts.
 Continuous Integration – We can achieve nightly execution using Jenkins.

13. What is Selenium?


Selenium is an open source (free) automated testing suite to test web applications. It supports different platforms and
browsers. It has gained a lot of popularity in terms of web-based automated testing and giving a great competition to the
famous commercial tool HP QTP (Quick Test Professional) AKA HP UFT (Unified Functional Testing).

Selenium is a set of different software tools. Each tool has a different approach in supporting web based automation
testing.

It has four components namely,

1. Selenium IDE (Selenium Integrated Development Environment)


2. Selenium RC (Selenium Remote Control)
3. Selenium WebDriver
4. Selenium Grid

14. What is Selenium IDE?


Selenium IDE (Integrated Development Environment) is a Firefox plugin. It is the simplest framework in the Selenium
Suite. It allows us to record and playback the scripts. Even though we can create scripts using Selenium IDE, we need to
use Selenium RC or Selenium WebDriver to write more advanced and robust test cases.

15. What is Selenese?


Selenese is the language that is used to write test scripts in Selenium IDE.

16. Which is the only browser that supports Selenium IDE to be used?
Firefox and Chrome. However, as Selenium IDE is community-powered, regular updates and compatibility with new
browser versions cannot be ensured.

Back in 2017 when it no longer worked with Firefox’s latest version, users switched to Katalon Recorder. It supports the
same commands, extension scripts, data-driven testing, and advanced test reporting platform with TestOps.

Check out Best Chrome Extensions for Software Testers

17. What is Selenium RC?


Selenium RC AKA Selenium Remote control / Selenium 1. Selenium Remote Control was the main Selenium project for a
long time before the WebDriver merge brought up Selenium 2. Selenium 1 is still actively supported (in maintenance
mode). It relies on JavaScript for automation. It supports Java, Javascript, Ruby, PHP, Python, Perl, and C#. It supports
almost every browser out there.

18. What is Selenium WebDriver?


Selenium WebDriver AKA Selenium 2 is a browser automation framework that accepts commands and sends them to a
browser. It is implemented through a browser-specific driver. It controls the browser by directly communicating with it.
Selenium WebDriver supports Java, C#, PHP, Python, Perl, Ruby.

Learn Selenium WebDriver Architecture

19. What is the difference between Selenium 3 and Selenium 4?


We all know that Selenium 4 was released as a stable version on October 13, 2021. So here in this post, we have covered
Selenium 4 Interview Questions & Answers. First Let’s see the difference between Selenium 3 and Selenium 4.
Selenium 3 – JSON wire protocol was used to communicate between the Selenium Webdriver APIs and the browser
native APIs. All the requests and responses communicated across the protocol were encoded & decoded.

Selenium 4 – Follows the W3C standard protocol. Due to this request and the response communicated across the
protocol doesn’t require the encoding and decoding API.

Checkout new features of Selenium 4

20. What is Selenium Grid?


Selenium Grid is a tool used together with Selenium RC to run tests on different machines against different browsers in
parallel. That is, running multiple tests at the same time against different machines running different browsers and
operating systems.

In simple words, it is used to distribute your test execution on multiple platforms and environments concurrently.

21. When do you use Selenium Grid?


Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as
to achieve distributed test execution

22. What are the advantages of Selenium Grid?


It allows running test cases in parallel thereby saving test execution time.
It allows multi-browser testing
It allows us to execute test cases on multi-platform

23. What is a hub in Selenium Grid?


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

24. What is a node in Selenium Grid?


Node is the machine which is attached to the hub. There can be multiple nodes in Selenium Grid.

25. What are the types of WebDriver APIs available in Selenium?


 Firefox Driver
 Gecko Driver
 InternetExplorer Driver
 Chrome Driver
 HTMLUnit Driver
 Opera Driver
 Safari Driver
 Android Driver
 iPhone Driver
 EventFiringWebDriver

26. Which WebDriver implementation claims to be the fastest?


The fastest implementation of WebDriver is the HTMLUnitDriver. It is because the HTMLUnitDriver does not execute tests
in the browser. Starting a browser and running test cases took more time compared to running the scripts without a
browser. HTMLUnitDriver took a simple HTTP request-response mechanism for test case execution.

Learn more on How To Do Headless Browser Testing using Selenium WebDriver

27. What are the Programming Languages supported by Selenium WebDiver?


 Java
 C#
 Python
 Ruby
 Perl
 PHP

28. Which language is not supported by selenium?


Selenium supports all major programming languages such as Java, C#, Perl, Python, Ruby, PHP, Scala and Groovy. As of
today, others are not compatible.

29. What are the Operating Systems supported by Selenium WebDriver?


 Windows
 Linux
 Mac OS X
 iOS
 Android

30. What are the testing types that can be supported by selenium?
Testing types that can be supported by Selenium are as follows:

 Functional Testing
 Regression Testing
 Retesting
 Acceptance Testing
 End-to-End Testing
 Smoke Testing
 Sanity Testing
 Responsive Testing
 Cross Browser Testing
 UI Testing
 Integration Testing

31. How many parameters can selenium commands have at minimum?


There are four parameters that you have to pass in Selenium are

 Host
 Port Number
 Browser
 URL

Host: It is the parameter which we use to bind Selenium to a specific IP. Usually, we run selenium tests on our local
machine so the value will be ‘localhost’. You can sepcify IP address instead of localhost.

java -jar <selenium server standalone jar name> -host <Your IP Address>

Port Number: TCP/IP port which is used to connect selenium tests to the selenium grid hub. Default port hub is 4444.
java -jar <selenium server standalone jar name> -role hub -port 4444

Make sure no other application in your system is using this port. You may face an exception like Exception in thread
“main” java.net.BindException: Selenium is already running on port 4444. Or some other service is.

If this occurs you can either shutdown the other process that is using port 4444, or you can tell Selenium-Grid to use a
different port for its hub. Use the -port option for changing the port used by the hub.

java -jar <selenium server standalone jar name> -role hub -port 4441

Browser: To pass the browser which has to execute our selenium scripts

URL: To pass the application URL

32. What are the Open-source Frameworks supported by Selenium WebDriver?


 JUnit
 TestNG

Read: TestNG Complete Tutorial

33. What are the Locators available in Selenium?


In Selenium WebDriver, there are 8 different types of locators:

1. ID – Practical example
2. ClassName – Practical example
3. Name – Practical example
4. TagName – Practical example
5. LinkText – Practical example
6. PartialLinkText – Practical example
7. XPath – Practical example
8. CSS Selector – Practical example

Click here to see the detailed post on Locators.

34. What is an XPath?


XPath is used to locate the elements. Using XPath, we could navigate through elements and attributes in an XML
document to locate web elements such as textbox, button, checkbox, Image etc., in a web page.

Learn How To Write Dynamic XPath

35. When you use these locators ID, Name, XPath, Or CSS Selector?
ID & Name locators will be used when there are unique identifiers & unique names available on the web page.
CSS Selector can be used for performance and when ID & Name locators are not unique.
XPath is used when there is no preferred locators.

36. What is the difference between “/” and “//”


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.

37. What is the difference between Absolute Path and Relative Path?
Absolute XPath starts from the root node and ends with desired descendant element’s node. It starts with top HTML node
and ends with input node. It starts with a single forward slash(/) as shown below.

/html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input
Relative XPath starts from any node in between the HTML page to the current element’s node(last node of the
element). It starts with a double forward slash(//) as shown below.

//input[@id='email']

38. What should you do when even XPath functions can’t identify the web
element?
In the early stages of software developement, developers change identifiers and elements quite often. During the
execution, the web elements may change dynamically and we cannot identify the web elements. To overcome this we use
XPath axes along with XPath functions.

39. What are XPath Axes?


XPath axes are used to search for the multiple nodes in the XML document from the context (current) node.
XPath axes are used to find dynamic elements that would otherwise be impossible using standard locators.

40. What is a Context Node?


The context node is the node the XPath processor is currently looking at.

41. What is the difference between Assert and Verify in Selenium?


Assert: In simple words, if the assert condition is true then the program control will execute the next test step but if the
condition is false, the execution will stop and further test step will not be executed.

Verify: In simple words, there won’t be any halt in the test execution even though the verify condition is true or false.

Read this detailed post on Assert vs Verify with practical example here detailed post check the below link.

42. What are Soft Assert and Hard Assert in Selenium?


Soft Assert: Soft Assert collects errors during @Test Soft Assert does not throw an exception when an assert fails and would
continue with the next step after the assert statement.

Hard Assert: Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues
with next @Test

Detailed Post: Soft Assert

43. What is the difference between setSpeed () and sleep () methods?


Both sleep() and setSpeed() are used to delay the execution speed.

setSpeed(): It set up speed that will apply a delay time before every Selenium operation.

Example: setSpeed(“5000”) – It waits for 5 seconds

sleep(): It set up wait only for once when called in our Selenium script.

Example: sleep(5000) – It waits for 5 seconds

Note: setSpeed method is applicable to Selenium IDE and Selenium RC. We cannot use setSpeed in Selenium WebDriver.

44. What are the verification points available in Selenium?


In Selenium IDE, we use Selenese Verify and Assert Commands as Verification points
In Selenium WebDriver, there is no built-in features for verification points. It totally depends on our coding style. some of
the Verification points are

 To check for page title


 To check for certain text
 To check for certain element (text box, button, drop down, etc.)

45. How to launch a browser using Selenium WebDriver?


WebDriver is an Interface. We create an Object of a required driver class such as FirefoxDriver, ChromeDriver,
InternetExplorerDriver etc.,

To launch Firefox Driver:


WebDriver driver = new FirefoxDriver();

Note: If you use geckodriver with Selenium, you must upgrade to Selenium 3.3. Here we have to set the property as follows

System.setProperty("webdriver.gecko.driver", "D:\\Selenium Environment\\Drivers\\geckodriver.exe");


To launch Chrome Driver:
WebDriver driver = new ChromeDriver();
To launch Internet Explorer Driver:
WebDriver driver = new InternetExplorerDriver();

To launch Safari Driver:


WebDriver driver = new SafariDriver();

46. Is the FirefoxDriver a Class or an Interface?


FirefoxDriver is a Java class, and it implements the WebDriver interface.

47. What is the super interface of WebDriver?


SearchContext acts as the super interface of Web Driver.

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


Webdriver driver = new FirefoxDriver();
‘WebDriver‘ is an interface and we are creating an object of type WebDriver instantiating an object of FirefoxDriver class.

Read more on why WebDriver driver = new FirefoxDriver();

49. We do create a reference variable ‘driver’ of type WebDriver as shown below.


What is the purpose of doing this way?
WebDriver driver = new FirefoxDriver();

instead of creating

FirefoxDriver driver = new FirefoxDriver();


If we create a reference variable driver of type WebDriver then we could use the same driver variable to work with any
browser of our choice such as IEDriver, SafariDriver etc.,

50. What is WebElement selenium?


WebElement in Selenium represents an HTML element. It basically represents a DOM element in a HTML document.

51. What are the different exceptions you have faced in Selenium WebDriver?
Some of the exceptions I have faced in my current project are

1. ElementNotVisibleException
2. StaleElementReferenceException

Element Not visible Exception:

This exception will be thrown when you are trying to locate a particular element on webpage that is not currently visible
eventhough it is present in the DOM. Also sometimes, if you are trying to locate an element with the xpath which
associates with two or more element.

Stale Element Reference Exception:

A stale element reference exception is thrown in one of two cases, the first being more common than the second.

The two reasons for Stale element reference are

1. The element has been deleted entirely.


2. The element is no longer attached to the DOM.

We face this stale element reference exception when the element we are interacting is destroyed and then recreated
again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the
reference to the element.
Some other exceptions we usually face are as follows:

 WebDriverException
 IllegalStateException
 TimeoutException
 NoAlertPresentException
 NoSuchWindowException
 NoSuchElementException

52. How to handle STALEELEMENTREFERENCEEXCEPTION?


Before looking how to handle Stale Element Reference Exception through Page Object Model. Let’s see what is Stale
Element Reference Exception first.

Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element. Assume
there is an element that is found on a web page referenced as a WebElement in WebDriver. If the DOM changes then the
WebElement goes stale. If we try to interact with an element which is staled then the StaleElementReferenceException is
thrown.

Here we have given solutions to handle StaleElementReferenceException in detail.

53. What are the types of waits available in Selenium WebDriver?


In Selenium we could see three types of waits such as Implicit Waits, Explicit Waits and Fluent Waits.

 Implicit Waits – Click to view detailed post


 Explicit Waits – Click to view detailed post
 Fluent Waits – Click to view detailed post

54. What is Implicit Wait In Selenium WebDriver?


Implicit waits tell to the WebDriver to wait for a certain amount of time before it throws an exception. Once we set the
time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0
(zero). We need to set some wait time to make WebDriver to wait for the required time.

Practical example

55. What is WebDriver Wait In Selenium WebDriver?


WebDriverWait is applied on a certain element with defined expected condition and time. This wait is only applied to the
specified element. This wait can also throw an exception when an element is not found.

Practical example

56. What is Fluent Wait In Selenium WebDriver?


FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check
the condition before throwing an “ElementNotVisibleException” exception.

Practical example

57. What happen if you mix both implicit wait and explicit wait in a Selenium
Script?
As per the official Selenium documentation, it is suggested not to mix both Implicit waits and Explicit Waits. Mixing both
of them can cause unpredictable wait times.

Implicit wait is defined only once in the code. It will remain same throughout the driver object instance.

Explicit wait is defined whenever it is necessary in the code. This wait will call at the time of execution. It is a conditional
wait.

Explicit wait will overwrite the implicit wait where ever explicit wait is applied. So, Explicit Wait gets first preference then
Implicit Wait.

58. What happen if you mix both Thread.Sleep and WebDriver Waits in a
Selenium Script?
Thread.sleep() method can be used to pause the execution for specified time in milliseconds

If we use WebDriver waits along with Thread.sleep() method then webdriver will hold the execution for specified time and
then will follow other wait. Test execution time will become more, if we mix both waits.

59. How to Login into any site if it is showing an Authentication Pop-Up for
Username and Password?
To do this we pass username and password with the URL

http://username:password@url
e.g. http://myUserName:myPassword@softwaretestingmaterial.com

60. How to input text in the text box using Selenium WebDriver?
By using sendKeys() method

WebDriver driver = new FirefoxDriver();


driver.get("https://www.gmail.com");
driver.findElement(By.xpath("xpath")).sendKeys("Software Testing Material Website");

61. How to input text in the text box without calling the sendKeys()?
// To initialize js object
JavascriptExecutor JS = (JavascriptExecutor)webdriver;
// To enter username
JS.executeScript("document.getElementById('User').value='SoftwareTestingMaterial.com'");
// To enter password
JS.executeScript("document.getElementById('Pass').value='tester'");
Learn JavaScriptExecutor in Selenium with Examples

62. How to clear the text in the text box using Selenium WebDriver?
By using clear() method

WebDriver driver = new FirefoxDriver();


driver.get("https://www.gmail.com");
driver.findElement(By.xpath("xpath_of_element1")).sendKeys("Software Testing Material Website");
driver.findElement(By.xpath("xpath_of_element1")).clear();

63. How to get a text of a web element?


By using getText() method

package softwareTestingMaterial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class TestTestTest {

@Test
public void testmethod(){
System.setProperty("webdriver.chrome.driver", "D:\\Selenium Environment\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
String availableText = driver.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[1]/a")).getText();
System.out.println("Text Available is :"+availableText);
}
}

64. How to get an attribute value using Selenium WebDriver?


By using getAttribute(value);

It returns the value of the attribute passed as a parameter.

HTML:

<input name="nameSelenium" value="valueSelenium">SoftwareTestingMaterial</input>


Selenium Code:

String attributeValue = driver.findElement(By.name("nameSelenium")).getAttribute("value");


System.out.println("Available attribute value is :"+attributeValue);
Output: valueSelenium

65. How to click on a hyperlink using Selenium WebDriver?


We use click() method in Selenium to click on the hyperlink

driver.findElement(By.linkText(“Software Testing Material Website”)).click();

66. How to submit a form using Selenium WebDriver?


We use “submit” method on element to submit a form

driver.findElement(By.id("form_1")).submit();
Alternatively, you can use click method on the element which does form submission

67. How to press ENTER key on text box In Selenium WebDriver?


To press ENTER key using Selenium WebDriver, We need to use Selenium Enum Keys with its constant ENTER.

driver.findElement(By.xpath("xpath")).sendKeys(Keys.ENTER);

68. How to pause a test execution for 5 seconds at a specific point?


By using java.lang.Thread.sleep(long milliseconds) method we could pause the execution for a specific time. To pause 5
seconds, we need to pass parameter as 5000 (5 seconds)

Thread.sleep(5000)

69. Is Selenium Server needed to run Selenium WebDriver Scripts?


When we are distributing our Selenium WebDriver scripts to execute using Selenium Grid, we need to use Selenium
Server.

70. What happens if I run this


command. driver.get(“www.softwaretestingmaterial.com”) ;
If the URL doesn’t contain http or https prefix then an exception is thrown. So, we need to pass HTTP protocol within
driver.get() method.

driver.get("https://www.softwaretestingmaterial.com");

71. What is the alternative to driver.get() method to open an URL using Selenium
WebDriver?
Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)

72. What is the difference between driver.get() and driver.navigate.to(“url”)?


driver.get(): To open an URL and it will wait till the whole page gets loaded
driver.navigate.to(): To navigate to an URL and It will not wait till the whole page gets loaded

73. Can I navigate back and forth in a browser in Selenium WebDriver?


We use Navigate interface to do navigate back and forth in a browser. It has methods to move back, forward as well as to
refresh a page.

driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history
driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history
driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements
driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL

74. What are the different types of navigation commands?


Refer above question (Can I navigate back and forth in a browser)

75. How to fetch the current page URL in Selenium?


To fetch the current page URL, we use getCurrentURL()

driver.getCurrentUrl();

76. How can we maximize browser window in Selenium?


To maximize browser window in selenium we use maximize() method. This method maximizes the current window if it is
not already maximized

driver.manage().window().maximize();

77. How to delete cookies in Selenium?


To delete cookies we use deleteAllCookies() method

driver.manage().deleteAllCookies();

78. What are the ways to refresh a browser using Selenium WebDriver?
There are multiple ways to refresh a page in selenium

 Using driver.navigate().refresh() command as mentioned in the question 45


 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());
 Using sendKeys(Keys.F5) on any textbox on the webpage

79. What is the difference between driver.getWindowHandle() and


driver.getWindowHandles() in Selenium WebDriver?
driver.getWindowHandle() – It returns a handle of the current page (a unique identifier)
driver.getWindowHandles() – It returns a set of handles of the all the pages available.

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


Purpose of these two methods (driver.close and driver.quit) is almost same. Both allow us to close a browser but still,
there is a difference.

driver.close(): To close current WebDriver instance


driver.quit(): To close all the opened WebDriver instances

81. 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.

82. What Is The Difference Between MaxSessions Vs. MaxInstances Properties in


Selenium Grid?
MaxInstances is the no. of browser instances of the same version of the browser that can run on the remote machine.

Let’s see an example below:

-browser browserName=InternetExplorer,version=6,maxInstances=2,platform=WINDOWS
-browser browserName=firefox,version=11,maxInstances=2,platform=WINDOWS
As per the above example, it will allow us to run 4 instances of both IE and Firefox at the same time (in parallel) in a
remote machine.

MaxSession says how many browsers, independent of the type & version, can run in parallel on the remote machine.

It supersedes the “MaxInstances” setting.

If maxSession=1 then no more than a single browser would run. If maxSession=2 then any of the below combinations can
run at a time irrespective of what MaxInstances we have defined.
2 Internet Explorer
2 Firefox
1 Internet Explorer + 1 Firefox

83. How to find whether an element is displayed on the web page?


WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements
can be buttons, drop boxes, checkboxes, radio buttons, labels etc.

1. isDisplayed()

boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();

2. isSelected()

boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected();

3. isEnabled()

boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();

84. How to select a value in a dropdown?


By using Select class

WebElement mySelectElement = driver.findElement(By.name("dropdown"));


Select dropdown = new Select(mySelectElement);
dropdown.selectByVisibleText(Text);
dropdown.selectByIndex(Index);
dropdown.selectByValue(Value);
Practical Example:

85. How to capture Screenshot in Selenium WebDriver?


Test cases may fail while executing the test scripts. While we are executing the test cases manually we just take a
screenshot and place in a result repository. The same can be done by using Selenium WebDriver.

Some of the scenarios we may need to capture a screenshot using Selenium WebDriver are
i. Application issues
ii. Assertion Failure
iii. Difficulty to find Webelements on the web page
iv. Timeout to find Webelements on the web page

Selenium provides an interface called TakesScreenshot which has a method getScreenShotAs which can be used to take a
screenshot of the application under test.

In Selenium 3, we may face few issues while capturing Screenshots. To overcome we use aShot utility. Click on below links
to see posts related to the normal way of capturing a screenshot and capturing a screenshot using aShot utility.

 Capture screenshot using Selenium WebDriver


 Full Page Screenshot using aShot utility
 Failed Test Cases Screenshot

86 How to mouse hover on a web element using WebDriver?


By using Actions class

WebElement ele = driver.findElement(By.xpath("xpath"));


//Create object 'action' of an Actions class
Actions action = new Actions(driver);
//Mouseover on an element
action.moveToElement(ele).perform();
Practical Example.

87. How can we handle Web-based Pop-ups or Alerts in Selenium?


To handle Web-based alerts or popups, we need to do switch to the alert window and call Selenium WebDriver Alert API
methods.

dismiss(): To click on Cancel button.


accept(): To Click on OK button.
getText(): To get the text which is present on the Alert.
sendKeys(): To enter the text into the alert box.

Practical Example.

88. How can we handle windows based pop up?


Selenium doesn’t support windows based applications. It is an automation testing tool which supports only web
application testing. We could handle windows based popups in Selenium using some third party tools such as AutoIT,
Robot class etc.

89. How to handle hidden elements in Selenium WebDriver?


We can handle hidden elements by using javaScript executor

(JavascriptExecutor(driver)).executeScript("document.getElementsByClassName(ElementLocator).click();");

90. How can you find Broken Links in a page using Selenium WebDriver?
Practical Example.

91. How to find more than one web element in the list?
// To store the list
List <WebElement> eleList = driver.findElements(By.xpath("xpath"));
// To fetch the size of the list
int listSize = eleList.size();
//for loop
for (int i=0; i<listSize; i++)
{
// Clicking on each link
links.get(i).click();
// Navigating back to the previous page that stores the links
driver.navigate().back();
}
92. How to read a JavaScript variable in Selenium WebDriver?
By using JavascriptExecutor

// To initialize the JS object.


JavascriptExecutor JS = (JavascriptExecutor) webdriver;
// To get the site title.
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);

93. What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in


Selenium automation?
In general, we click on an element using click() method in Selenium.

For example:

driver.findElement(By.id("Id Value")).click();
Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement
(click()). To overcome such kind of situation, we use JavaScriptExecutor interface.

It provides a mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript”
methods, to run JavaScript in the context of the currently selected frame or window.

There is no need to write a separate script to execute JavaScript within the browser using Selenium WebDriver script. Just
we use predefined interface named ‘Java Script Executor’. We need to import the JavascriptExecutor package in the script.

Package:

import org.openqa.selenium.JavascriptExecutor;
Syntax:

JavascriptExecutor js = (JavascriptExecutor) driver;


js.executeScript(Script,Arguments);
Script – The JavaScript to execute
Arguments – The arguments to the script(Optional). May be empty.
Returns – One of Boolean, Long, String, List, WebElement, or null.

Let’s see some scenarios we could handle using this Interface:

1. To type Text in Selenium WebDriver without using sendKeys() method


2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate Alert Pop window in selenium
5. To refresh browser window using Javascript
6. To get innertext of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using Selenium
11. To click on a SubMenu which is only visible on mouse hover on Menu
12. To navigate to different page using Javascript

94. How do you read test data from excels?


Test data can efficiently be read from excel using JXL or POI API. POI API has many advantages than JXL.
Click here to see a practical example of using Apache POI.

95. Is it possible to automate the captcha using Selenium?


No, It’s not possible to automate captcha and bar code reader.

96. Can You Use Selenium For Rest API Testing Or Web Services Testing?
Simple answer for this is Selenium is not a tool for API Testing. It automates web browsers. Rest API & Web Services
contains no UI. So we cannot automate using Selenium.
Don’t miss: API Testing Interview Questions

97. How to handle Ajax calls in Selenium WebDriver?


Handling AJAX calls is one of the common issues when using Selenium WebDriver. We wouldn’t know when the AJAX call
would get completed and the page has been updated. In this post, we see how to handle AJAX calls using Selenium.

AJAX stands for Asynchronous JavaScript and XML. AJAX allows the web page to retrieve small amounts of data from the
server without reloading the entire page. AJAX sends HTTP requests from the client to server and then process the
server’s response without reloading the entire page. To handle AJAX controls, wait commands may not work. It’s just
because the actual page is not going to refresh.

When you click on a submit button, the required information may appear on the web page without refreshing the
browser. Sometimes it may load in a second and sometimes it may take longer. We have no control over loading time.
The best approach to handle this kind of situations in selenium is to use dynamic waits (i.e. WebDriverWait in
combination with ExpectedCondition)

Some of the methods which are available are as follows:

1. titleIs() – The expected condition waits for a page with a specific title.

wait.until(ExpectedConditions.titleIs(“Deal of the Day”));


2. elementToBeClickable() – The expected condition waits for an element to be clickable i.e. it should be
present/displayed/visible on the screen as well as enabled.

wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));
3. alertIsPresent() – The expected condition waits for an alert box to appear.

wait.until(ExpectedConditions.alertIsPresent()) !=null);
4. textToBePresentInElement() – The expected condition waits for an element having a certain string pattern.

wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));

98. List some scenarios which we cannot automate using Selenium WebDriver?
1. Bitmap comparison is not possible using Selenium WebDriver
2. Automating Captcha is not possible using Selenium WebDriver
3. We can not read bar code using Selenium WebDriver

99. What is Object Repository in Selenium WebDriver?


Object Repository is used to store element locator values in a centralized location instead of hard coding them within the
scripts. We do create a property file (.properties) to store all the element locators and these property files act as an object
repository in Selenium WebDriver.

100. How you build Object Repository in your project?


In QTP, there is an Object Repository concept. When a user records a test, the objects and its properties are captured by
default in an Object Repository. QTP uses this Object Repository to play back the scripts.

Coming to Selenium, there is no default Object Repository concept. It doesn’t mean that there is no Object Repository in
Selenium. Even though there is no default one still we could create our own. In Selenium, we call objects as locators (such
as ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, XPath, and CSS).

Object repository is a collection of objects. One of the ways to create Object Repository is to place all the locators in a
separate file (i.e., properties file). But the best way is to use Page Object Model.

In the Page Object Model Design Pattern, each web page is represented as a class. All the objects related to a particular
page of a web application are stored in a class.
101. What is Page Object Model in Selenium?
Page Object Model is a Design Pattern which has become popular in Selenium Test Automation. It is widely used design
pattern in Selenium for enhancing test maintenance and reducing code duplication.

Page object model (POM) can be used in any kind of framework such as modular, data-driven, keyword driven, hybrid
framework etc.

A page object is an object-oriented class that serves as an interface to a page of your Application Under Test(AUT). The
tests then use the methods of this page object class whenever they need to interact with the User Interface (UI) of that
page.

The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the
page object needs to change. Subsequently, all changes to support that new UI is located in one place.

102. What is Page Factory?


We have seen that ‘Page Object Model’ is a way of representing an application in a test framework. For every ‘page’ in the
application, we create a Page Object to reference the ‘page’ whereas a ‘Page Factory’ is one way of implementing the
‘Page Object Model’.

103. What is the difference between Page Object Model (POM) and Page Factory?
Page Object is a class that represents a web page and hold the functionality and members.
Page Factory is a way to initialize the web elements you want to interact with within the page object when you create an
instance of it.

104. What are the advantages of Page Object Model Framework?


Code reusability – We could achieve code reusability by writing the code once and use it in different tests.

Code maintainability – There is a clean separation between test code and page specific code such as locators and layout
which becomes very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It
enhances test maintenance and reduces code duplication.

Object Repository – Each page will be defined as a java class. All the fields in the page will be defined in an interface as
members. The class will then implement the interface.

Readability – Improves readability due to clean separation between test code and page specific code

105. How can you use the Recovery Scenario in Selenium WebDriver?
By using “Try Catch Block” within Selenium WebDriver Java tests.

try {
driver.get("www.softwaretestingmaterial.com");
}catch(Exception e){
System.out.println(e.getMessage());
}

106. How to Upload a file in Selenium WebDriver?


There are two cases which are majorly used to upload a file in Selenium WebDriver such as using SendKeys Method and
using AutoIT Script.

Practical Example.

107. How to Download a file in Selenium WebDriver?


By using AutoIT script, we could download a file in Selenium WebDriver.

Practical Example

108. How to run Selenium WebDriver Test from the command line?
 Run Java Program using Command Prompt
 Run TestNG using Command Prompt

109. How to switch between frames in Selenium?


By using the following code, we could switch between frames.

driver.switchTo().frame();

110. How to connect a Database in selenium?


As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using
Selenium WebDriver.

We use JDBC Driver to connect the Database in Selenium (While using Java Programming Language).

Practical Example

111. How To Resize Browser Window Using Selenium WebDriver?


To resize the browser window to particular dimensions, we use ‘Dimension’ class to resize the browser window.

Practical Example

112. How To Scroll Web Page Down Or UP Using Selenium WebDriver?


JavaScript scrollBy() method scrolls the document by the specified number of pixels.

Practical Example

113. How To Perform Right Click Action (Context Click) In Selenium WebDriver?
We use Actions class in Selenium WebDriver to do Right-Click (Context Click) action.

Practical Example

114. How To Perform Double Click Action In Selenium WebDriver?


We use Actions class to do Double click action in selenium.

Practical Example

115. How To Perform Drag And Drop Action in Selenium WebDriver?


In some applications, we may face a situation to automate drag and drop an item from one location to another
location. We could not achieve these using basic elements. Selenium has provided an “Actions” class to handle this kind
of scenarios. We overcome this kind of scenarios such as drag and drop using Actions Class.

To achieve this, we use Actions class in Selenium WebDriver.

Practical Example

116. How To Highlight Element Using Selenium WebDriver?


By using JavascriptExecutor interface, we could highlight the specified element

Practical Example

117. Have you used any crossbrowsertesting tool to run selenium scripts on
cloud?
I have used BrowserStack to run selenium tests on multiple browsers & Multiple operating systems in parallel. Earlier we
have made a video on how to use BrowserStack to run selenium scripts on the cloud. Find the link in the description
below.

118. What is desired capabilities?


In Selenium we use desired capabilities to handle SSL certificates in chrome browser

We need to create an instance of DesiredCapabilities

DesiredCapabilities desiredCapability = DesiredCapabilities.chrome();

119. What is Continuous Integration?


Continuous Integration is abbreviated as CI. Continuous Integration is a development practice that aims to make sure the
correctness of software. After each commit, a suite of tests run automatically and test the software to ensure whether the
software is running without any breaks. If any test fails, we will get immediate feedback say “build is broken”.

In simple words, continuous integration is a process of verifying the correctness of a software.

Some of the continuous integration tools are Jenkins, TeamCity, Bamboo, Travis, Circle Ci, Bitbucket.

We can schedule the test suite execution using these CI Tools.

Learn how Continuous Integration with Jenkins in Selenium works

120. Name some CI tools available in the Market?


Some of the best continuous testing softwares to use in your project.

 Selenium
 Katalon Studio
 Appium
 Unified Functional Testing
 Travis CI
 Egg Plant
 Watir
 Tricentis Tosca
 Test Sigma
 IBM Rational Functional Tester
 Test Complete
 QuerySurge
 JMeter
 Jenkins
 Bamboo
 Docker
 PagerDuty
 JIRA
 GitHub

Read the detailed explanation on Continuous Testing Tools

121. How to achieve Database testing in Selenium?


As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using
Selenium WebDriver.

Sometimes, we may face a situation to get the data from the Database or to modify (update/delete) the data from the
Database. If we plan to automate anything outside the vicinity of a browser, then we need to use other tools to achieve
our task.
To achieve the Database connection and work on it, we need to use JDBC API Driver.

The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language.

Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. It
lets the user connect and interact with the Database and fetch the data based on the queries we use in the automation
script.

JDBC is a SQL level API that allows us to execute SQL statements. It creates a connectivity between Java Programming
Language and the database.

Using JDBC Driver we could do the following

i. Establish a Database connection


ii. Send SQL Queries to the Database
iii. Process the results

122. How to delete Browser Cookies with Selenium Web Driver?


driver.Manage().Cookies.DeleteAllCookies();

TestNG Interview Questions:


Here we have dealt with some important TestNG interview questions. If you want to learn more interview questions
related to TestNG then here you go. We have a special post on TestNG Interview Questions. Also, you could find TestNG
Complete Tutorial here

123. What is TestNG?


TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing to integration
testing.

124. What are the types of annotations available in TestNG?


@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@BeforeSuite
@AfterSuite
@BeforeGroups
@AfterGroups
@Test

125. What is TestNG Assert and list out some common Assertions supported by
TestNG?
TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions,
we will consider a successful test only if it is completed the test run without throwing any exception.

Some of the common assertions supported by TestNG are

 assertEqual(String actual,String expected)


 assertEqual(String actual,String expected, String message)
 assertEquals(boolean actual,boolean expected)
 assertTrue(condition)
 assertTrue(condition, message)
 assertFalse(condition)
 assertFalse(condition, message)

For Complete Post


126. How to create and run TestNG.xml?
In TestNG framework, we need to create TestNG XML file to create and handle multiple test classes. We do configure our
test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the XML file.

For Complete Post

127. How to set test case priority in TestNG?


We use priority attribute to the @Test annotations. In case priority is not set then the test scripts execute in alphabetical
order.

package TestNG;
import org.testng.annotations.*;
public class PriorityTestCase{
@Test(priority=0)
public void testCase1() {
system.out.println("Test Case 1");
}
@Test(priority=1)
public void testCase2() {
system.out.println("Test Case 2");
}
}
Output:

Test Case 1
Test Case 2

128. What is Parameterized testing in TestNG?


Parameterized tests allow developers to run the same test over and over again using different values.

There are two ways to set these parameters:

 with testng.xml - Practical Example


 with Data Providers – Practical Example

129. How to run a group of test cases using TestNG?


TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to
groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a
certain set of groups (or regular expressions) while excluding another set.

This gives you maximum flexibility in how you partition your tests and doesn’t require you to recompile anything if you
want to run two different sets of tests back to back.

Groups are specified in your testng.xml file and can be found either under the <test> or <suite> tag. Groups specified in
the <suite> tag apply to all the <test> tags underneath.

@Test (groups = { "smokeTest", "functionalTest" })


public void loginTest(){
System.out.println("Logged in successfully");
}
View Complete Post

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


Ans. TestNG listeners are used to configure reports and logging. One of the most widely used listeners in TestNG
is ITestListener interface. It has methods like onTestStart, onTestSuccess, onTestFailure, onTestSkipped etc. We
should implement this interface creating a listener class of our own. Next, we should add the listeners annotation
(@Listeners) in the Class which was created.

Practical Example

131. How can we create a data-driven framework using TestNG?


By using @DataProvider annotation, we can create a Data-Driven Testing Framework.

@DataProvider(name="getData")
public Object[][] getData(){
//Object [][] data = new Object [rowCount][colCount];
Object [][] data = new Object [2][2];

data [0][0] = "FirstUid";


data [0][1] = "FirstPWD";

data[1][0] = "SecondUid";
data[1][1] = "SecondPWD";

return data;

}
Practical Example

132. Where you have applied OOPS in Automation Framework?


Here we have given a clear explanation of the application of OOPs in Automation Framework

133. How to handle browser (chrome) notifications in Selenium?

In Chrome, we can use ChromeOptions as shown below.

ChromeOptions options = new ChromeOptions();


options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);
I would like to conclude this post here. Final words, Bookmark this post “Selenium Testing Interview Questions” for future
reference. We keep on updating this post based on user requests.

134. Mention types of data you have handled in Selenium?


 Excel
 CSV
 XML
 JSON
 YAML
 SQL

1. What is a Framework?

A framework defines a set of rules or best practices which we can follow in a systematic way to achieve the desired
results.

2. Tell me some popular Test Automation Frameworks?

There are different types of test automation frameworks and the most common ones are:

 Modular Testing Framework


 Data Driven Testing Framework
 Keyword Driven Testing Framework
 Hybrid Testing Framework
 Behavior Driven Development Framework
Detailed Post on Types of Automation Frameworks

3. Why Framework?

In a test automation project, we do perform different tasks by using different types of files. To organize and manage all
the files and to finish all the tasks in a systematic approach we use a framework.

4. Have you created any Framework?

If you are a beginner: No, I didn’t get a chance to create a framework. I have used the framework which is already
available.
If you are an experienced tester: Yes, I have created a framework (Or) No, but I have involved in the creation of
the framework.

5. What are the advantages of using Test Automation Framework?

1. Saves time and money. Automation testing is faster in execution


2. Reusability of code. Create one time and execute multiple times with less or no maintenance
3. Easy reporting. It generates automatic reports after test execution
4. Easy for compatibility testing. It enables parallel execution in combination of different OS and browser
environments
5. Low cost maintenance. It is cheaper compared to manual testing in a long run
6. Automated testing is more reliable
7. Automated testing is more powerful and versatile
8. It is mostly used for regression testing. Supports execution of repeated test cases
9. Minimal manual intervention. Test scripts can be run unattended
10.Maximum coverage. It helps to increase the test coverage

6. Which Test Automation Framework you are using and why?

Some of the Test Automation Frameworks are:

 Data Driven Testing Framework


 Keyword Driven Testing Framework
 Hybrid Testing Framework

7. Mention the name of the framework which ‘you are currently using’ or which ‘you have hands on experience’.

Example:
Answers should be, Already the organization which I am working for is using that particular framework or I have an
experience on that particular framework or It’s easy to handle all my scripts to execute and generate logs, screenshots and
reports by using this framework.

8. Can you explain the Framework which you have used in your Selenium Project?

Check this link for detailed answer

9. Where you have applied OOPs in your Automation Framework?

Check this link for detailed answer

Concepts of OOPS in Selenium Automation Framework


In this post, we will discuss how and where we applied following OOPs concepts in an Automation Framework.

Table of Contents

 Concepts of OOPS in Selenium Automation Framework


o #1. ABSTRACTION
o #2. INTERFACE
o #3. INHERITANCE
o #4. POLYMORPHISM
 #1. METHOD OVERLOADING
 #2. METHOD OVERRIDING
o #5. ENCAPSULATION
 Other Selenium Automation Framework Concepts
o #1. WEB ELEMENT
o #2. WEBDRIVER
o #3. FIND BY
o #4. FIND ELEMENT

#1. ABSTRACTION
Abstraction is the methodology of hiding the implementation of internal details and showing the functionality to the
users.

Let’s see an example of data abstraction in Selenium Automation Framework.

In Page Object Model design pattern, we write locators (such as id, name, xpath etc.,) and the methods in a Page Class.
We utilize these locators in tests but we can’t see the implementation of the methods. Literally we hide the
implementations of the locators from the tests.

Learn more on Abstraction

In Java, abstraction is achieved by interfaces and abstract classes. Using interfaces, we can achieve 100% abstraction.

Let’s see interface concept below.

#2. INTERFACE
Basic statement we all know in Selenium is WebDriver driver = new FirefoxDriver();

Detailed explanation on why we write WebDriver driver = new FirefoxDriver(); in Selenium.


WebDriver itself is an Interface. So based on the above statement WebDriver driver = new FirefoxDriver(); we are
initializing Firefox browser using Selenium WebDriver. It means we are creating a reference variable (driver) of
the interface (WebDriver) and creating an Object. Here WebDriver is an Interface as mentioned earlier and FirefoxDriver is
a class.

An interface in Java looks similar to a class but both the interface and class are two different concepts. An interface can
have methods and variables just like the class but the methods declared in interface are by default abstract. We can
achieve 100% abstraction and multiple inheritance in Java with Interface.

Learn more on Interface here.

#3. INHERITANCE
The mechanism in Java by which one class acquires the properties (instance variables) and functionalities of another class
is known as Inheritance.

We create a Base Class in the Automation Framework to initialize WebDriver interface, WebDriver waits, Property files,
Excels, etc., in the Base Class.

We extend the Base Class in other classes such as Tests and Utility Class.

Here we extend one class (Base Class like WebDriver Interface) into other class (like Tests, Utility Class) is known as
Inheritance.

Learn more on Inheritance here.

#4. POLYMORPHISM
Polymorphism allows us to perform a task in multiple ways.

Combination of overloading and overriding is known as Polymorphism. We will see both overloading and overriding
below.

Learn more on Polymorphism here.


#1. METHOD OVERLOADING
We use Implicit wait in Selenium. Implicit wait is an example of overloading. In Implicit wait we use different time stamps
such as SECONDS, MINUTES, HOURS etc.,

Action class in TestNG is also an example of overloading.

Assert class in TestNG is also an example of overloading.

A class having multiple methods with same name but different parameters is called Method Overloading

Learn more on Overloading here.

#2. METHOD OVERRIDING


We use a method which was already implemented in another class by changing its parameters. To understand this you
need to understand Overriding in Java.

Declaring a method in child class which is already present in the parent class is called Method Overriding. Examples
are get and navigate methods of different drivers in Selenium .

Learn more on Overriding with examples here

#5. ENCAPSULATION
All the classes in a framework are an example of Encapsulation. In POM classes, we declare the data members
using @FindBy and initialization of data members will be done using Constructor to utilize those in methods.

Encapsulation is a mechanism of binding code and data (variables) together in a single unit.

Learn more on Encapsulation here

10. What is Automation testing? What are the advantages of Automation Testing?

Automation testing is the process of testing the software using an automation tool to find the defects. In this process,
executing the test scripts and generating the results are performed automatically by automation tools. Some most
popular tools to do automation testing are HP QTP/UFT, Selenium WebDriver, etc.,

For advantages refer to question 5 of this post “Test Automation Framework Interview Questions”

11. What are the most popular testing tools for functional testing?

1. Selenium
2. QTP(Quick Test Professional) / UFT(Unified Functional Testing)

12. Why do you prefer Selenium Automation Tool?

1. Free and open source


2. Have large user base and helping communities
3. Cross-browser compatibility
4. Platform compatibility
5. Multiple programming languages support

13. What type of test cases do you pick up to automate?

I focus on the test cases which should be executed in a repetitive manner such as regression test cases, smoke and sanity
test cases

14. What type of test cases you won’t pick up to automate?


Before picking up the test cases to automate, I do check whether the application is stable or not. So based on this, I don’t
pickup test cases when the AUT changes frequently and the test cases which I run rarely and run only one time. When I
do usability and exploratory testing.

15. How many test cases you have automated per day?

It depends on Test case scenario complexity and length. I did automate 2-5 test scenarios per day when the complexity is
limited. Sometimes just 1 or fewer test scenarios in a day when the complexity is high.

16. How you build Object Repository in your project?

In QTP, there is an Object Repository concept. When a user records a test, the objects and its properties are captured by
default in an Object Repository. QTP uses this Object Repository to play back the scripts. Coming to Selenium, there is no
default Object Repository concept. It doesn’t mean that there is no Object Repository in Selenium. Even though there is
no default one still we could create our own. In Selenium, we call objects as locators (such as ID, Name, Class Name, Tag
Name, Link Text, Partial Link Text, XPath, and CSS). Object repository is a collection of objects. One of the ways to create
Object Repository is to place all the locators in a separate file (i.e., properties file). But the best way is to use Page Object
Model. In the Page Object Model Design Pattern, each web page is represented as a class. All the objects related to a
particular page of a web application are stored in a class.

If you have any other questions related to Test Automation Framework Interview Questions, please post it in the
comments box below and we will include those in this post.

Here I have hand-picked few posts which will help you to learn more interview related stuff:

 Selenium Interview Questions


 Test Automation Framework Interview Questions
 TestNG Interview Questions
 SQL Interview Questions
 Manual Testing Interview Questions
 Agile Interview Questions
 Why You Choose Software Testing As A Career
 General Interview Questions

If you have any more question, feel free to ask via comments. If you find this post useful, do share it with your friends on
Social Networking.

1. What is TestNG?

TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing to integration
testing. For more information.

2. What are the advantages of TestNG?

1. TestNG provides parallel execution of test methods


2. It allows to define dependency of one test method over other method
3. It allows to assign priority to test methods
4. It allows grouping of test methods into test groups
5. It has support for parameterizing test cases using @Parameters annotation
6. It allows data driven testing using @DataProvider annotation
7. It has different assertions that helps in checking the expected and actual results
8. Detailed (HTML) reports

3. What are the annotations available in TestNG?

@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@BeforeSuite
@AfterSuite
@BeforeGroups
@AfterGroups
@Test

Practical Example

4. Can you arrange the below testng.xml tags from parent to child?

<test>
<suite>
<class>
<methods>
<classes>
The correct order of the TestNG tags are as follows

<suite>
<test>
<classes>
<class>
<methods>
5. How to create and run testng.xml ?

In TestNG framework, we need to create testng.xml file to create and handle multiple test classes. We do configure our
test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the xml file.

View Complete Post

6. What is the importance of testng.xml file?

In a Selenium TestNG project, we use testng.xml file to configure the complete test suite in a single file. Some of the
features are as follows.

 testng.xml file allows to include or exclude the execution of test methods and test groups
 It allows to pass parameters to the test cases
 Allows to add group dependencies
 Allows to add priorities to the test cases
 Allows to configure parallel execution of test cases
 Allows to parameterize the test cases

7. How to pass parameter through testng.xml file to a test case?

We could define the parameters in the testng.xml file and then reference those parameters in the source files.

Create a java test class, say, ParameterizedTest.java and add a test method say parameterizedTest() to the test class. This
method takes a string as input parameter. Add the annotation @Parameters(“browser”) to this method.

// TestNG Interview Questions


public class ParameterizedTest {
@Test
@Parameters("browser")
public void parameterizedTest(String browser){
if(browser.equals("firefox")){
System.out.println("Open Firefox Driver");
}else if(browser.equals("chrome")){
System.out.println("Open Chrome Driver");
}
}
}
The parameter would be passed a value from testng.xml, which we will see in the next step.

We could set the parameter using the below syntax in the testng.xml file.

<parameter name="browser" value="firefox"/>


Here, name attribute represents the parameter name and value represents the value of that parameter.

Practical Example
8. What is TestNG Assert and list out common TestNG Assertions?

TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions,
we will consider a successful test only if it is completed the test run without throwing any exception.

Some of the common assertions supported by TestNG are

 assertEqual(String actual,String expected)


 assertEqual(String actual,String expected, String message)
 assertEquals(boolean actual,boolean expected)
 assertTrue(condition)
 assertTrue(condition, message)
 assertFalse(condition)
 assertFalse(condition, message)

For Complete Post

9. What is Soft Assert in TestNG?

Soft Assert collects errors during @Test. Soft Assert does not throw an exception when an assert fails and would continue
with the next step after the assert statement.

If there is any exception and you want to throw it then you need to use assertAll() method as a last statement in the
@Test and test suite again continue with next @Test as it is.

Practical Example

10. What is Hard Assert in TestNG?

Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues with next @Test

Practical Example

11. What is exception test in TestNG?

TestNG gives an option for tracing the Exception handling of code. You can verify whether a code throws the expected
exception or not. The expected exception to validate while running the test case is mentioned using
the expectedExceptions attribute value along with @Test annotation.

Practical Example

12. How to set test case priority in TestNG?

We use priority attribute to the @Test annotations. In case priority is not set then the test scripts execute in alphabetical
order.

// TestNG Interview Questions


package TestNG;
import org.testng.annotations.*;
public class PriorityTestCase{
@Test(priority=0)
public void testCase1() {
system.out.println("Test Case 1");
}
@Test(priority=1)
public void testCase2() {
system.out.println("Test Case 2");
}
}
Output:

Test Case 1
Test Case 2
13. What is Parameterized testing in TestNG?

Parameterized tests allow developers to run the same test over and over again using different values.

There are two ways to set these parameters:


 using testng.xml – Practical Example
 using Data Providers – Practical Example

14. How can we create data driven framework using TestNG?


By using @DataProvider annotation, we can create a Data Driven Framework.

// TestNG Interview Questions


@DataProvider(name="getData")
public Object[][] getData(){
//Object [][] data = new Object [rowCount][colCount];
Object [][] data = new Object [2][2];

data [0][0] = "FirstUid";


data [0][1] = "FirstPWD";

data[1][0] = "SecondUid";
data[1][1] = "SecondPWD";

return data;

}
Practical Example

15. How to run a group of test cases using TestNG?

TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to
groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a
certain set of groups (or regular expressions) while excluding another set. This gives you maximum flexibility in how you
partition your tests and doesn’t require you to recompile anything if you want to run two different sets of tests back to
back.

Groups are specified in your testng.xml file and can be found either under the <test> or <suite> tag. Groups specified in
the <suite> tag apply to all the <test> tags underneath.

@Test (groups = { "smokeTest", "functionalTest" })


public void loginTest(){
System.out.println("Logged in successfully");
}
Practical Example

TestNG Interview Questions 16 – 33


16. How to create Group of Groups in TestNG?

Groups can also include other groups. These groups are called MetaGroups. For example, you might want to define a
group all that includes smokeTest and functionalTest. Let’s modify our testng.xml file as follows:

<groups>
<define name="all">
<include name="smokeTest"/>
<include name="functionalTest"/>
</define>
<run>
<include name="all" />
</run>
</groups>
Practical Example

17. How to run test cases in parallel using TestNG?

we can use “parallel” attribute in testng.xml to accomplish parallel test execution in TestNG

The parallel attribute of suite tag can accept four values:

tests – All the test cases inside <test> tag of testng.xml file will run parallel
classes – All the test cases inside a java class will run parallel
methods – All the methods with @Test annotation will execute parallel
instances – Test cases in same instance will execute parallel but two methods of two different instances will run in
different thread.
<suite name="softwaretestingmaterial" parallel="methods">
Practical Example

18. How to exclude a particular test method from a test case execution?

By adding the exclude tag in the testng.xml

<classes>
<class name="TestCaseName">
<methods>
<exclude name="TestMethodNameToExclude"/>
</methods>
</class>
</classes>
19. How to exclude a particular test group from a test case execution?

By adding the exclude tag in the testng.xml

<groups>
<run>
<exclude name="TestGroupNameToExclude"/>
</run>
</groups>
Practical Example

20. How to disable a test case in TestNG ?

To disable the test case we use the parameter enabled = false to the @Test annotation.

@Test(enabled = false)
21. How to skip a @Test method from execution in TestNG?

By using throw new SkipException()

Once SkipException() thrown, remaining part of that test method will not be executed and control will goes directly to
next test method execution.

throw new SkipException("Skipping - This is not ready for testing ");


Practical Example

22. How to Ignore a test case in TestNG?

To ignore the test case we use the parameter enabled = false to the @Test annotation.

@Test(enabled = false)
Practical Example

23. How TestNG allows to state dependencies?

TestNG allows two ways to declare the dependencies.

Using attributes dependsOnMethods in @Test annotations – Practical Example


Using attributes dependsOnGroups in @Test annotations – Practical Example

24. What are the different ways to produce reports for TestNG results?

TestNG offers two ways to produce a report.

Listeners implement the interface org.testng.ITestListener and are notified in real time of when a test starts, passes, fails,
etc…

Reporters implement the interface org.testng.IReporter and are notified when all the suites have been run by TestNG. The
IReporter instance receives a list of objects that describe the entire test run.

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

TestNG listeners are used to configure reports and logging. One of the most widely used listeners in testNG
is ITestListener interface. It has methods like onTestStart, onTestSuccess, onTestFailure, onTestSkipped etc. We
should implement this interface creating a listener class of our own. Next we should add the listeners annotation
(@Listeners) in the Class which was created.
Practical Example

26. How to write regular expression In testng.xml file to search @Test methods containing “smoke” keyword.

Regular expression to find @Test methods containing keyword “smoke” is as mentioned below.
<methods>
<include name=".*smoke.*"/>
</methods>
27. What is the time unit we specify in test suites and test cases?

We specify the time unit in test suites and test cases is in milliseconds.

28. List out various ways in which TestNG can be invoked?

TestNG can be invoked in the following ways

 Using Eclipse IDE


 Using ant build tool
 From the command line
 Using IntelliJ’s IDEA

29. How To Run TestNG Using Command Prompt?

Run the TestNG using command prompt

Open command prompt and use the below code

C:\Users\Admin\Desktop\STMSeleniumTutorial\workspace\SoftwareTestingMaterial

set classpath=C:\Users\Admin\Desktop\STMSeleniumTutorial\workspace\SoftwareTestingMaterial\bin;C:\Users\Admin\Desktop\STMSeleniumTutorial\workspace\
SoftwareTestingMaterial\lib\*

java org.testng.TestNG C:\Users\Admin\Desktop\STMSeleniumTutorial\workspace\SoftwareTestingMaterial\testng.xml


30. What is the use of @Test(invocationCount=x)?

The invocationcount attribute tells how many times TestNG should run a test method

@Test(invocationCount = 10)
public void testCase1(){
In this example, the method testCase1 will be invoked ten times

31. What is the use of @Test(threadPoolSize=x)?

The threadPoolSize attribute tells to form a thread pool to run the test method through multiple threads.

Note: This attribute is ignored if invocationCount is not specified

@Test(threadPoolSize = 3, invocationCount = 10) public void testCase1(){


In this example, the method testCase1 will be invoked from three different threads

32. What does the test timeout mean in TestNG?

The maximum number of milliseconds a test case should take.

@Test(threadPoolSize = 3, invocationCount = 10, timeOut = 10000)


public void testCase1(){
In this example, the function testCase1 will be invoked ten times from three different threads. Additionally, a time-out of
ten seconds guarantees that none of the threads will block on this thread forever.

33. What are @Factory and @DataProvider annotation?

@Factory: A factory will execute all the test methods present inside a test class using a separate instance of the respective
class with different set of data.

@DataProvider: A test method that uses DataProvider will be executed the specific methods multiple number of times
based on the data provided by the DataProvider. The test method will be executed using the same instance of the test
class to which the test method belongs.

I would like to conclude this post “TestNG Interview Questions” here.


Final words, Bookmark this post “TestNG Interview Questions” for future reference. After reading this post “TestNG
Interview Questions”, if you find that we missed some important questions, please comment below we would try to
include those with answers.

Page Object Model Framework with Java and WebDriver


Further reading:

 Selenium Tutorial: Learn UI Browser Automation

CI/CD Interview Questions

1. What is CI/CD pipeline?

CI/CD is a combination of continuous integration (CI) and continuous delivery (usually) or continuous deployment (rarely) in
software engineering. Modern DevOps operations are built on the foundation of continuous integration and continuous delivery,
or the CI/CD pipeline. You can automate your software delivery process with a CI/CD pipeline. As part of the pipeline, code is
built, tests are run (CI), and a new version of the application is safely deployed (CD). By automating pipelines, manual errors are
eliminated, developers are provided with standardized feedback loops, and iterating on products is made more efficient. In
DevOps, continuous integration and continuous delivery (CI/CD) are best practices that ensure that code changes are delivered
regularly and reliably.

2. Explain Continuous Integration, Continuous Delivery, and Continuous Deployment.

 Continuous Integration (CI): Continuous integration (CI) is the practice of developers regularly integrating their code changes into a
repository. Integration may take place several times a day and is verified by automated tests and a build process. As a result, integration
challenges can be avoided, bugs can be found early in the development cycle, fixed, and tested iteratively. Every time new commits are
integrated into the main branch, continuous integration emphasizes testing automation to make sure the application is not broken.
 Continuous Delivery (CD): In continuous delivery, all code changes are automatically deployed to the test and/or production environments
after the build is complete. Feature additions, configuration changes, and error fixes are some examples of changes. By automating the
delivery of new code to users, CD ensures a safe, quick, sustainable process. The CD process also involves some additional checks, like
performance tests in production. With Continuous Delivery, deployments are predictable and scheduled regularly.
 Continuous Deployment (CD): The most critical stage of the pipeline is continuous deployment. By following this practice, you will be able
to release all changes that have passed all stages of the production pipeline to your customers on time. Code changes can be made live
much more quickly at this stage because there is little human interaction. In addition, continuous deployment allows you to accelerate your
feedback loop with your customers and relieve pressure on your team since "release days" are no longer needed. Minutes after finishing their
work, developers see their work go live.

3. Explain the benefit of the CI/CD Pipeline.

CI/CD brings certain benefits to your organization that will help you decide whether to go ahead with it. Below are some of these
benefits:

 CI/CD makes it possible to quickly integrate small code changes and test the changes easily.
 With CI/CD setup, fault isolation is easier and faster. In fault isolation, the system is monitored, the fault occurrence time is determined, and
the fault location is determined.
 With CI/CD, MTTR (mean time to resolution) is reduced since changes are smaller and easier to implement. CI/CD setup increases the
reliability of the unit and integration testing.
 When CI/CD is set up, small code changes are merged very quickly and the code is ready for production very soon.
 CI improves transparency by detecting early-stage failures like build failures, merge issues, integration test failures, etc.
 CD facilitates the release of code to end-users.

You can download a PDF version of Ci Cd Interview Questions.

Download PDF

4. What is a CI/CD Engineer?


CI/CD engineers can improve the integration and operation of CI/CD tools as well as ensure quality end-to-end integration
systems. CI/CD Engineers would keep teams motivated and lead the charge on CI/CD. It is the CI/CD engineer's responsibility to
ensure that CI/CD tools and platforms are functioning correctly within an organization. CI/CD engineers understand how to
optimize their teams' development and release processes.

5. State difference between CI/CD vs DevOps.

DevOps and CI/CD differ in the following ways:

CI/CD DevOps

The DevOps methodology is an approach to


An important feature of CI/CD is its ability to automate and deliver code changes
streamlining the development of products by
quickly and reliably.
integrating ideas, practices, processes, and technology.

CI/CD involves continuous automation and monitoring of the entire application lifecycle, Organizations can implement DevOps methodologies
starting with integration and testing and ending with delivery and deployment. As a to encourage rapid, continuous deployment of
result of CI/CD pipelines, organizations are able to minimize bottlenecks during software software by setting up their production teams and
development and deployment. processes.

A continuous integration process optimizes the process of building, integrating, and


DevOps promotes minimizing waste and creating
testing code in a development environment. Continuous delivery is concerned with
scalable, enduring systems.
deploying code effectively in production.

6. What are some popular CI/CD tools?

Some popular CI/CD tools are as follows:

 Jenkins
 CircleCI
 Bamboo
 Team City
 Codefresh

7. Does CI/CD require any programming knowledge?

As far as CI/CD goes, it does not require any programming language or scripting language to be used. It is not necessary to use
any programming or scripting language when you use a GUI-based tool like Azure DevOps (ADO). The use of ARM templates in
Azure DevOps requires scripting knowledge. Therefore, it depends on the tools and different ways of setting up CI/CD.

8. What is Version Control?

Version control involves the use of a central repository where teammates can commit changes to files and sets of files. The
purpose of version control is to track every line of code, and to share, review, and synchronize changes between team members.
The following are some of the most popular version control tools:

 Mercurial
 Subversion (SVN)
 Concurrent Version Systems (CVS)
 Perforce
 Bazaar
 Bitkeeper
 Fossil

9. Explain Git.

It is a distributed version control system that keeps track of changes to code repositories. As projects progress, Git uses a branch-
based workflow to streamline team collaboration. Learn More.

10. What do you mean by Git Repository?

As part of the software development process, software projects are organized through Git repositories. In the repository,
developers can keep track of all the files and changes in the project, so that they can navigate to any point in its history at any
time.

11. Can you explain the Git branch?


The Git branch is essentially a separate line of development that can be used for working on a particular feature, usually during
development. The use of branches allows developers to code without interfering with the work of other team members.

12. What is the importance of DevOps?

A robust and flexible product deployment system is essential for organizations to remain competitive in today's digitized world. It
is here that the DevOps concept comes into play.

 The DevOps approach plays a crucial role in generating agility and mobility across all aspects of software development, from conception to
deployment.
 Continuously updating and improving products is more streamlined and efficient with DevOps.
 By implementing DevOps, developers increase their focus on building only code, while automating and consolidating the remaining tasks.
 In addition to creating better communication and collaboration, combining the engineering and operations teams increase transparency and
accessibility.
 Increasing efficiency speeds up development and reduces coding errors.
 Programming defects are the most common cause of development failures. DevOps teams will facilitate more releases in a shorter time
frame.

13. Describe the build stage.

The build stage is the first phase of the CI/CD pipeline, and it automates a lot of the steps that a typical developer goes through,
such as installing tools, downloading dependencies, and compiling a project. Aside from building code, build automation involves
the use of tools to verify that the code is safe and compliant with best practices. In this stage, the buildability and testability of
the application are validated.

14. What does containerization mean?

As the term implies, containerization entails packaging together software code along with all the necessary components, such as
frameworks, libraries, and other dependencies, in their own container. Among the advantages of containerization is that a
container can be viewed as a fully packaged computing environment that can be transported in one piece.

15. Explain Docker.

As its name implies, Docker is a containerization platform that packages applications and their dependencies together in
containers to ensure that the applications run seamlessly across multiple environments. Docker containers are entire file systems
that contain all the components for running a piece of software: code, system tools, runtime, system libraries, etc. Any software
that can be installed on a server can be packaged in a Docker container. It ensures that the software always runs the same in any
environment.

16. State differences between a docker image and a container.

The following are the differences between Docker images and containers:

Docker Container Docker Image

Docker Containers are actually Docker Virtual Machines. Essentially, a Docker Images are templates containing instructions for creating
image is a map of the house, while a Docker container is the actual house itself, containers. With Docker images, containers can be created to
so we can call it an instance of an image. run on the Docker platform.

It is a real-world entity. It is a logical entity.

Using images, containers can be created as many times as necessary. An image is only created once.

In order for containers to change, the old image must be deleted and a new one
There is no change to the image. It is immutable.
must be used to build the containers.

A container requires computing resources to run since it runs as a Docker Virtual


Computing resources aren't required to work with images.
Machine.

Creating a Docker image requires writing a script in a


Run the "docker build." command to build a container from an image.
Dockerfile.

In order to function, containers utilize server information and file systems You can use Docker images to package up applications and
provided by docker images. pre-configured server environments.
CI/CD Interview Questions for Experienced

17. Explain trunk-based development.

The trunk-based development approach ensures software remains up-to-date by integrating small, frequent updates into the
main branch or a core "trunk". As a result of its ability to streamline merging and integration phases, it can be used to achieve
CI/CD and to increase the speed and efficiency of the delivery of software and the efficiency of organizations. It is a branching
model that consists of most of the work happening in a single trunk (also known as the trunk, master, or main). Each developer in
the team merges their changes into the trunk on a daily basis. The reason why trunk-based development is popular is that it
simplifies version control. This model minimizes merge conflicts due to the trunk's single source of truth.

18. Can a branch live for a long time?

Continuous integration follows trunk-based development practices, which means branches should be short-lived. Branch
durations should be kept to a minimum of a few hours and a maximum of a day.

19. What is the difference between a hosted and a cloud-based CI/CD platform?

Hosted and Cloud-based CI/CD platforms differ in the following ways:

Hosted CI/CD platform Cloud-based CI/CD platform

It is necessary to manage a hosted CI server in the same way as Cloud-based CI platforms, however, do not require maintenance. An
any other server. Installation, configuration, and maintenance are organization can immediately start using CI/CD platforms in the cloud
all required before they can be used. without installing or configuring anything.

As the cloud is capable of providing all the machine power necessary,


Keeping the server secure requires updates and patches.
scalability is not an issue.

Additionally, failures in the CI server can halt development and The cloud SLA (service-level agreement) guarantees the reliability of the
deployment. platform.

20. In CI/CD, does security play an important role? How does it get secured?

There are many factors that affect the security of CI/CD pipelines. These include:

 The importance of unit testing cannot be overstated when it comes to the testing of multiple unit-testable distributed components. It is
therefore important to unit test your code properly.
 Static analysis security testing (SAST) scans your code for security vulnerabilities and the libraries you use. To ensure SAST scanning, all
modern tools integrate well with the CD pipeline.
 DAST (dynamic analysis security testing) is a tool for securing your application by dynamically scanning for security vulnerabilities. It
simulates the actions of an attacker by performing the tests outside the application.

21. Explain some common practices of CI/CD.

To help you establish an efficient pipeline for CI/CD, here are some best practices:

 Embrace the DevOps culture.


 Ensure continuous integration is implemented and utilized.
 Ensure the same deployment process is followed for every environment.
 In the event that your pipeline fails, restart it.
 Version control should be applied.
 Incorporate the database into the pipeline.
 Keep an eye on your continuous delivery pipeline.
 Get your CD pipeline up and running.

22. In what way does testing fit into continuous integration? Is automated testing always a good idea?

The testing process is inextricably linked to continuous integration. Continuous feedback is the main benefit of CI for teams. Code
developers test their code in the CI to ensure that it behaves as expected. Without testing, there would be no feedback loop to
determine whether the application is release-ready.

23. Why is Automated Testing essential for CI/CD?

In order to ensure code quality, automation is an important characteristic of the CI/CD pipeline. The test automation process is
used throughout the software development pipeline to identify dependencies and other issues, push changes to the different
environments, and deploy applications into production. As part of its quality control role, the automation will assess everything
from API usage and performance to security. In this manner, all changes made by team members are integrated comprehensively
and implemented correctly.

 With automated testing, we can run tests simultaneously across multiple servers/containers, resulting in a faster testing process.
 Automated testing provides more consistency. Software automation eliminates human errors, and bias, and assures that it behaves as
expected.
 To meet changing demands, tools and frameworks in a CI/CD pipeline need to be adjusted quickly. Keeping up with updates and being agile
is difficult with manual testing. However, most configurations are done automatically when you have automated tests. This allows you to
migrate quickly to new environments.
 Maximizing the workforce is crucial to a successful development project. Test automation frees engineers to work on other high-value tasks.
 CI/CD pipelines require all the testing effort when small changes are made. Validating minor changes continuously is easier with automated
testing.

24. What are the top testing tools in continuous testing?

An essential part of the CI/CD pipeline is continuous testing (CT). The developers are buffered by it, as it squashes bugs in a
timely manner. This ensures that no matter how many releases take place, the end-user experience remains uncompromised.
Despite accelerated processes, CT serves as a safety net that preserves the end-user experience. It must be seamlessly integrated
into the software delivery pipeline since it is a continuous process. The following are the top testing tools used in continuous
testing:

 Testsigma
 Selenium
 IBM Rational Functional Tester
 Tricentis Tosca
 UFT (Unified Functional Testing)

25. How do DevOps tools work together?

A generic logical flow is shown below that automates it to ensure smooth delivery. Organizations may follow different flows
depending on their needs.

 Developers create code, and a version control system, such as Git, manages the source code.
 Any modifications made to this code are committed to the Git repository by developers.
 Jenkins extracts the code from the repository and builds it using software such as Ant or Maven using the Git plugin.
 Puppet is used to deploy and configure test environments, and Jenkins releases this code to the test environment so that testing can be
conducted using Selenium tools.
 Jenkins deploys the code once it has been tested on the production server (even the production servers are managed by resources like a
puppet).
 Nagios, for example, continuously monitors it after deployment.
 Using Docker containers, we can test the build features in a controlled environment. Learn More.

26. What are some of the deployment strategies?

 Regular release/deployment: Through a single release, the software is made available to the public.
 Canary releases: These releases are intended to reduce the risk of failure by exposing a small fraction of the user base (around 1%) to the
release. As part of a canary release, developers gradually transition users to the new release in a controlled manner.
 Blue-green releases: Essentially, it involves running two instances of an application simultaneously; one is the current stable version, and the
other is the most recent version. An immediate switch is made from the old version to the new one. If there is a problem, users can
immediately revert to the previous version, which is safer than regular or big-bang releases.

27. Can you tell me about the serverless model?

There is a cloud-native approach to development known as serverless development, which allows developers to develop and run
applications without requiring the management of servers. The server still exists serverless, but it is abstracted from application
development.

28. Explain OpenShift Container Platform.

OpenShift Container Platform is a PAAS service offered by RedHat, formerly called OpenShift Enterprises. Additionally, Open
Shift offers auto-scaling, self-healing, and highly available applications without the need to manually set them up in a traditional
environment, even if they're on-premises or in the cloud. The OpenShift platform supports a wide variety of open-source
programming languages, giving developers a polyglot choice.

29. What do you mean by Rolling Strategy?

Rolling deployments update running instances of an application with new releases as they are released. The process involves
replacing old versions of an application over time with new versions of the application by replacing the entire infrastructure on
which the application is run.
30. Describe Chef?

Chef is essentially an automation platform for turning infrastructure into code. A chef is a tool used to automate processes with
scripts. There are three main components of Chef that can be categorized as follows:

 Chef Workstation: The workstation is the computer system on which the administrator sits. This system generates code for configuring and
managing infrastructure, known as recipes (written in Ruby). A cookbook consists of multiple recipes. In order to upload cookbooks to the
server, the Knife command line tool is used.
 Chef Server: Second, a server resides between a workstation and its nodes, which stores the cookbooks. Servers provide the tools necessary
to enable node configurations, and they may be locally or remotely hosted.
 Chef Node: The final component is the node, which requires configuration. You can have a number of Chef nodes that collect information
about the current state of a node. The server then compares this information with the configuration files to determine if any new
configuration is needed.

Most Asked Cucumber Interview Questions


Following is the list of most frequently asked Cucumber Interview questions and their best possible answers.

1) What is Cucumber? Why is it used?


Cucumber is a testing tool based on Behavior Driven Development (BDD) framework. It is used to run functional tests written in
plain text and develop test cases for software functionality. It plays a supporting role in automated testing.

In other words, we can say that "Cucumber is a software tool used by the testers to develop test cases for the testing of behavior of
the software."

2) In which language is Cucumber software written?


Cucumber software is written in a Ruby programming language.

68.1M

1.3K

C++ vs Java

3) What is the main aim of the Behavior Driven Development (BDD) framework?
The main aim of the Behavior Driven Development framework is to make various project roles such as Business Analysts, Quality
Assurance, Developers, etc., understand the application without diving deep into the technical aspects.

4) What language is used by the Cucumber tool?


The Cucumber tool uses the Gherkin language, a simple English representation of the application behaviour. The Gherkin language
uses several keywords to describe the behaviour of applications such as Feature, Scenario, Scenario Outline, Given, When, Then, etc.

5) What are the two files required to execute a Cucumber test scenario?
Following are the two files required to execute a Cucumber test scenario:

o Features
o Step Definition

6) What do you understand by a feature file?


A feature file is used to provide a high-level description of an Application Under Test (AUT). The first line of the feature file must
start with the keyword 'Feature' followed by the description of the application under test. A feature file may include multiple
scenarios within the same file, and the extension of the feature file must be ".feature."

7) What are the various keywords used in the Cucumber tool for writing a
scenario?
Following are the keywords that are used for writing a scenario in the Cucumber tool:

o Given
o When
o Then
o And

8) What is the use of the Background keyword in Cucumber?


In the Cucumber tool, the Background keyword is used to group multiple given statements into a single group. The keyword is
mostly used when the same set of given statements are repeated in each scenario of the feature file.

9) What is the usage of a Scenario Outline in the Cucumber tool?


In Cucumber, a Scenario outline is used as a parameter of scenarios. This is used when the same scenario needs to be executed for
multiple sets of data; however, the test steps remain the same. Scenario Outline must be followed by the keyword 'Examples', which
specify the set of values for each parameter.

10) What do you understand by the term step definition in Cucumber?


In Cucumber, a step definition is the actual code implementation of the feature mentioned in the feature file.

11) Which programming languages are supported by Cucumber?


The Cucumber tool supports multiple programming languages such as Java, .Net, Ruby, etc. You can also integrate this tool easily
with multiple tools such as Selenium, Capybara, etc.

12) What are the differences between Jbehave and Cucumber?


Although Cucumber and Jbehave are designed for the same purpose, the most distinctive difference between them is that Jbehave
is based on stories while Cucumber is based on features.

13) What do you understand by regular expressions?


A regular expression is a pattern used to describe a certain amount of text. The most basic regular expression consists of a single
literal character.

14) What software is used to run a Cucumber Web Test case?


Following software is used to run a Cucumber Web Test case:
o Cucumber
o Ruby and its Development Kit
o IDE like ActiveState
o Watir ( To simulate browser)
o Ansicon and RSpec (if required)

15) What are the most significant advantages of the Cucumber framework?
Following is the list of advantages of the Cucumber framework that makes Cucumber an ideal choice for rapidly evolving agile
methodology in today's corporate world:

o Cucumber is an open-source and free-to-use tool.


o It is easy to use. Even non-technical users can also understand the scenarios because of its plain text representation.
o It bridges the communication gap between various project stakeholders such as Business Analysts, Developers, and Quality Assurance
personnel.
o With the Cucumber tool, we can develop automation test cases that are easier to maintain and understand.
o It is easy to integrate with other tools such as Selenium and Capybara.

16) What do you understand by test harness in Cucumber?


In Cucumber, the test harness allows for separating responsibility between setting up the context and interacting with the browser,
and cleaning up the step definition files. It collects stubs, drivers, and other supporting tools required to automate test execution in
testing.

17) What is the difference between RSpec and Cucumber? When should we use
RSpec and when to use Cucumber?
RSpec and Cucumber both are the example of testing frameworks. RSpec uses traditional Unit Testing. It means it uses testing a
class or part of the application in isolation from the rest of the application. So your model does what your model is supposed to do,
the controller does what it is supposed to do, etc. RSpec and Cucumber both are used for Acceptance Testing, also called ATDD,
BDD, etc.

Difference between RSpec and Cucumber

o The main difference between RSpec and Cucumber is the business readability factor.
o RSpec is mainly used for Unit Testing. On the other hand, Cucumber is mainly used for Behavior-driven development. We can also use it
for System and Integration Testing.
o In Cucumber, the specifications or features are separate from the test code, so the product owners can provide or review the
specification without going through the code. These are the .feature files that you make in Cucumber.
o RSpec also has a similar mechanism, but instead of describing a step with a Describe or Context, it uses the business specification to
execute that statement. This approach is a little easier for developers to work with but a bit harder for non-technical guys.

Which should we use?

o For a core developer, it is the best choice to use RSpec. It is easier to understand for a technical person and offers a few advantages in
keeping things scoped and under control because you don't have to mess up with RegExs for test steps.
o If you are building this for a client, you should choose Cucumber for Acceptance Testing and use RSpec for Unit Testing.

18) What is Selenium?


Selenium is a web browser automation tool widely used for Functional Testing of web-based applications. Selenium supports
different programming languages such as Java, Python, Ruby, C#, etc.
19) What is the difference between Selenium and Cucumber?
Selenium and Cucumber are both open-source testing tools, and both are used for functional testing. But there are some
differences between them.

Following are some critical differences between Selenium and Cucumber:

o Selenium is a web browser automation tool for web apps, while Cucumber is an automation tool for behavior-driven development that
can be used with Selenium (or Appium).
o Selenium is used for automated UI testing, while Cucumber is used for acceptance testing.
o Selenium is preferred by technical teams (SDETs/programmers), while Cucumber is typically preferred by non-technical teams (business
stakeholders and testers).
o Selenium can work independently of Cucumber. Cucumber depends on Selenium or Appium for step-definition implementation.
o In Selenium, the script creation is complex, while Cucumber is simpler than Selenium.

20) Why we have to use Cucumber with Selenium?


Cucumber and Selenium are both testing frameworks and prevalent technologies. Many organizations use Selenium for functional
testing. Along with Selenium, these organizations integrate Cucumber with Selenium as Cucumber makes it easy to read and
understand the application flow. The most significant benefit of using Cucumber with Selenium is that it facilitates developers to
write test cases in simple feature files easily understood by managers, non-technical stakeholders, and business analysts. It provides
the facility to write tests in a human-readable language called Gherkin. The Selenium-Cucumber framework supports programming
languages such as Java, .NET, PHP, Python, Perl, etc.

21) What do you understand by the Step Definition?


Step definition is used to map the Test Case Steps in the feature files to code. It executes the steps on Application under Test and
checks the results. To execute step definition, it must match the given component in a feature.

22) What are the maximum numbers of scenarios that we can includ in the
feature file?
In Cucumber, a feature file can contain a maximum of 10 scenarios. This number can vary from project to project and from one
organization to another organization. It is the best practice to limit the number of scenarios included in the feature file.

23) What is the purpose of the behavior-driven development (BDD) methodology


in the real world?
Behavior Driven Development or BDD is a methodology used to understand the functionality of an application in the simple plain
text representation. The primary purpose of the Behavior Driven Development framework is to make various project roles such as
Business Analysts, Quality Assurance, Developers, Support Teams understand the application without diving deep into the technical
aspects.

24) What do you understand by TDD, and what are the different processes used
in TDD?
TDD is an acronym that stands for Test-Driven Development. This is a software development technique used to create the test cases
first and then write the code underlying those test cases. Although TDD is a development technique, it can also be used for
automation testing development. TDD takes more time for development because it tends to find very few defects. The result
provided by the TDD development technique has improved the quality of code, and that can be more reusable and flexible. TDD
also helps developers to achieve high test coverage of about 90-100%. The only disadvantage for developers following TDD is to
write their test cases before writing the code.

Following is the list of simple 6 step process used by TDD methodology:

1. First, write the test case: You have to write an automated test case according to your requirements.
2. Run all the test cases: Now, run these automated test cases on the currently developed code.
3. Develop the code for that test case: In this process, you must write the code to make that test case work as expected if the test case
fails.
4. Run test cases again: Now, you have to rerun the test cases and check if all the test cases developed so far are implemented.
5. Refactor your code: This is an optional step. But, it is advised to refactor your code to make it more readable and reusable. That's why it
is essential.
6. Repeat steps 1- 5 for new test cases: This is the last step. Here, you have to repeat the cycle for the other test cases until all the test
cases are implemented.

25) What are the similarities between BDD and TDD?


TDD stands for Test-Driven Development, and BDD stands for Behavior Driven Development. Both are two software development
techniques.

BDD and TDD are both very similar as they are both testing strategies for a software application. In both cases, the developers have
to write the test before writing the code to pass the test. The second main similarity between them is in both cases; the tests can be
used as part of an automated testing framework to prevent bugs.

26) What are the main differences between TDD and BDD?
Following is the list of main differences between TDD and BDD:

TDD BDD

TDD stands for Test-Driven Development. It is a test- BDD stands for Behavior Driven Development. It is a Behavior
centered development process. This means the developers centered development process.
have first to write the test cases then code.

In TDD, writing a test fails because the specified In BDD, creating an executable specification that fails because the
functionality doesn't exist, then writing the most feature doesn't exist, then writing the most straightforward code
straightforward code that can make the test pass, then that can make the spec pass. You repeat this until a release
refactoring to remove duplication, etc. candidate is ready to ship.

TDD tests are written using programming languages such BDD tests are written in a human-readable format using Given-
as Java, .Net, Python, Ruby, etc. When-Then steps. These tests are readable and understandable by
non-technical persons also.

TDD tests are difficult to read by non-programmers as they BDD tests are readable by non-programmers also as they are
are written in specific programming languages. written in a human-readable format.

The critical difference between TDD and BDD is the scope. On the other hand, BDD is a team methodology.
TDD is a development practice.

In TDD, the developers write the test cases. In BDD, the automated specifications are created by users or
testers then the developers wiring them to the code under test.

27) What do you understand by cucumber dry run?


Cucumber dry run is used to compile cucumber features files and step definitions. It is run to find any compilation errors. If it finds
anyone, it will show when we use dry run.

28) What do you understand by the TestRunner class in the Cucumber testing
approach? Explain with example.
In the Cucumber testing approach, the TestRunner class provides the link between the feature file and the step definition file. The
TestRunner class is generally an empty class with no class definition.

Example of a TestRunner class in Cucumber:

1. Package com.sample.TestRunner
2. importorg.junit.runner.RunWith;
3. importcucumber.api.CucumberOptions;
4. importcucumber.api.junit.Cucumber;
5. @RunWith(Cucumber.class)
6. @CucumberOptions(features="Features",glue={"StepDefinition"})
7. public class Runner
8. {
9. }

29) Should we write code within the TestRunner class?


It is advised not to write code under the TestRunner class. It should include the tags @RunWith and @CucumberOptions.

30) What is the starting point of execution for feature files?


When Cucumber is integrated with Selenium, the starting point of execution must be from the TestRunner class.

31) How can you use the Options tag in the Cucumber framework?
In the Cucumber framework, the Options tag is a part of the TestRunner file and comes in the form of an annotation called
@CucumberOptions. It contains two parameters feature and glue.

o Feature parameter: The feature parameter is used to specify the path of the feature file.
o Glue parameter: The glue parameter is used to specify the path of the step definition file.

See the code implementation of TestRunner file with Option tag:

1. import org.junit.runner.RunWith;
2. import cucumber.api.CucumberOptions;
3. import cucumber.api.junit.Cucumber;
4. @RunWith (Cucumber.class)
5. @CucumberOptions (
6. features = "src/test/java/features ",
7. glue = {"stepDefinitions"}
8. )
9. public class TestRunner {
10. }

We have to import org.junit.runner.RunWith for the @RunWith annotation and cucumber.api.CucumberOptions for the
@CucumberOptions annotation.
32) What is the use of features property under the Cucumber Options tag?
In the Cucumber framework, the features property is used to identify the location of the feature files.

33) What is the use of glue property under the Cucumber Options tag?
The Glue property is used to facilitate the Cucumber framework to identify the location of step definition files.

34) What are the two build management tools that can be integrated with
Cucumber?
Following are the two build management tools that can be integrated with Cucumber:

o Gradle
o Maven

35) What is the use of hooks in the Cucumber framework?


In the Cucumber framework, the hooks are used to control the flow of the program and optimize lines of code. A block of code
tagged with hooks in Cucumber can run before or post a scenario with the help of @Before and @After annotations.

Some scenarios may require certain preconditions for execution, such as launching the application, establishing a database
connection, configuring the test data, and so on. Also, certain postconditions should be executed, such as terminating database
connection, closing the browser, refreshing test data, application log out, and so on. All these conditions are handled in Cucumber
with the help of the hooks. The @Before hook executes before the actual scenario, and the @After hook executes after the actual
scenario even if the test corresponding to the actual scenario fails.

For the @Before annotation, we have to import cucumber.api.java.en.Before and for the @After annotation, we have to import
cucumber.api.java.en.After.

Most Frequently Asked Cucumber Interview Questions


Q #1) Explain Cucumber shortly.
Answer: Cucumber is a tool that is based on Behavior Driven Development (BDD) methodology.
The main aim of the Behavior Driven Development framework is to make various project roles such as Business Analysts, Quality
Assurance, Developers, etc., understand the application without diving deep into the technical aspects.
Q #2) What language is used by Cucumber?
Answer: Gherkin is the language that is used by the Cucumber tool. It is a simple English representation of the application
behavior. Gherkin language uses several keywords to describe the behavior of applications such as Feature, Scenario, Scenario
Outline, Given, When, Then, etc.
Q #3) What is meant by a feature file?
Answer: A feature file must provide a high-level description of an Application Under Test (AUT). The first line of the feature file
must start with the keyword ‘Feature’ followed by the description of the application under test.
A feature file may include multiple scenarios within the same file. A feature file has the extension .feature.

Q #4) What are the various keywords that are used in Cucumber for writing a scenario?
Answer: Mentioned below are the keywords that are used for writing a scenario:
 Given
 When
 Then
 And
Q #5) What is the purpose of a Scenario Outline in Cucumber?
Answer: Scenario outline is a way of parameterization of scenarios. This is ideally used when the same scenario needs to be
executed for multiple sets of data, however, the test steps remain the same. Scenario Outline must be followed by the keyword
‘Examples’, which specify the set of values for each parameter.
Q #6) What programming language is used by Cucumber?
Answer: Cucumber tool provides support for multiple programming languages such as Java, .Net, Ruby etc. It can also be
integrated with multiple tools such as Selenium, Capybara, etc.
Q #7) What is the purpose of the Step Definition file in Cucumber?
Answer: A step definition file in Cucumber is used to segregate the feature files from the underlying code. Each step of the feature
file can be mapped to a corresponding method on the Step Definition file.
While feature files are written in an easily understandable language like, Gherkin, Step Definition files are written in programming
languages such as Java, .Net, Ruby, etc.
Q #8) What are the major advantages of the Cucumber framework?
Answer: Given below are the advantages of the Cucumber Gherkin framework that make Cucumber an ideal choice for rapidly
evolving Agile methodology in today’s corporate world.
 Cucumber is an open-source tool.
 Plain Text representation makes it easier for non-technical users to understand the scenarios.
 It bridges the communication gap between various project stakeholders such as Business Analysts, Developers, and Quality Assurance
personnel.
 Automation test cases developed using the Cucumber tool are easier to maintain and understand as well.
 Easy to integrate with other tools such as Selenium and Capybara.
Q #9) Provide an example of a feature file using the Cucumber framework.
Answer: Following is an example of a feature file for the scenario ‘Login into the application’:
Feature: Login to the application under test.
Scenario: Login to the application.
 Open the Chrome browser and launch the application.
 When the user enters the username onto the UserName field.
 And User enters the password into the Password field.
 When the user clicks on the Login button.
 Then validate if the user login is successful.
Q #10) Provide an example of a Scenario Outline using the Cucumber framework.
Answer: The following is an example of a Scenario Outline keyword for the scenario ‘Upload a file’. The number of parameter
values to be included in the feature file is based on the tester’s choice.
Scenario Outline: Upload a file
Given that the user is on upload file screen.
When a user clicks on the Browse button.
And user enters <filename> onto the upload textbox.
And user clicks on the enter button.
Then verify that the file upload is successful.

Example:
|filename|
|file1|
|file2|

Q #11) What is the purpose of the Behaviour Driven Development (BDD) methodology in the real world?
Answer: BDD is a methodology to understand the functionality of an application in the simple plain text representation.
The main aim of the Behavior Driven Development framework is to make various project roles such as Business Analysts, Quality
Assurance, Developers, Support Teams understand the application without diving deep into the technical aspects.

Q #12) What is the limit for the maximum number of scenarios that can be included in the feature file?
Answer: A feature file can contain a maximum of 10 scenarios, but the number can vary from project to project and from one
organization to another. But it is generally advisable to limit the number of scenarios included in the feature file.
Q #13) What is the use of Background keyword in Cucumber?
Answer: Background keyword is used to group multiple given statements into a single group. This is generally used when the
same set of given statements are repeated in each scenario of the feature file.
Q #14) What symbol is used for parameterization in Cucumber?
Answer: Pipe symbol (|) is used to specify one or more parameter values in a feature file.
Q #15) What is the purpose of Examples keyword in Cucumber?
Ans: Examples keyword is used to specify values for each parameter used in the scenario. Scenario Outline keyword must always
be followed by the keyword Examples.
Q #16) What is the file extension for a feature file?
Answer: File Extension for a feature file is .feature. A feature file is ideally written in a notepad file and is saved with the extension
feature.
Q #17) Provide an example of a step definition file in Cucumber.
Answer: Step definition corresponding to the step “Open Chrome browser and launch the application” may look like the code
mentioned below:
@Given("^Open Chrome browser and launch the application$")

public void openBrowser()

driver = new ChromeDriver();

driver.manage().window().maximize();

driver.get("www.facebook.com");

Q #18) What is the purpose of the Cucumber Options tag?


Answer: Cucumber Options tag is used to provide a link between the feature files and step definition files. Each step of the feature
file is mapped to a corresponding method on the step definition file.
Below is the syntax of Cucumber Options tag:
@CucumberOptions(features="Features",glue={"StepDefinition"})

Q #19) How can Cucumber be integrated with Selenium WebDriver?


Answer: Cucumber can be integrated with the Selenium Webdriver by downloading the necessary JAR files.
Given below are the list of JAR files that are to be downloaded for using Cucumber with Selenium web driver:
 cucumber-core-1.2.2.jar
 cucumber-java-1.2.2.jar
 cucumber-junit-1.2.2.jar
 cucumber-jvm-deps-1.0.3.jar
 cucumber-reporting-0.1.0.jar
 gherkin-2.12.2.jar
Q #20) When is Cucumber used in real-time?
Answer: Cucumber tool is generally used in real-time to write acceptance tests for an application. It is generally used by non-
technical people such as Business Analysts, Functional Testers, etc.
Q #21) Provide an example of Background keyword in Cucumber.
Answer:
Background: Given the user is on the application login page.
Q #22) What is the use of Behavior Driven Development in Agile methodology?
Answer: The advantages of Behavior Driven Development are best realized when non-technical users such as Business Analysts
use BDD to draft requirements and provide the same to the developers for implementation.
In Agile methodology, user stories can be written in the format of feature file and the same can be taken up for implementation by
the developers.

Q #23) Explain the purpose of keywords that are used for writing a scenario in Cucumber.
Answer:
 “Given” keyword is used to specify a precondition for the scenario.
 “When” keyword is used to specify an operation to be performed.
 “Then” keyword is used to specify the expected result of a performed action.
 “And” keyword is used to join one or more statements together into a single statement.
Q #24) What is the name of the plugin that is used to integrate Eclipse with Cucumber?
Answer: Cucumber Natural Plugin is the plugin that is used to integrate Eclipse with Cucumber.
Q #25) What is the meaning of the TestRunner class in Cucumber?
Answer: TestRunner class is used to provide the link between the feature file and the step definition file. The next question
provides a sample representation of how the TestRunner class will look like. A TestRunner class is generally an empty class with
no class definition.
Q #26) Provide an example of the TestRunner class in Cucumber.
Answer:
Package com.sample.TestRunner

importorg.junit.runner.RunWith;

importcucumber.api.CucumberOptions;

importcucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)

@CucumberOptions(features="Features",glue={"StepDefinition"})

public class Runner

Q #27) What is the starting point of execution for feature files?


Answer: When integrated with Selenium, the starting point of execution must be from the TestRunner class.
Q #28) Should any code be written within the TestRunner class?
Answer: No code should be written under the TestRunner class. It should include the tags @RunWith and @CucumberOptions.
Q #29) What is the use of features property under the Cucumber Options tag?
Answer: Features property is used to let the Cucumber framework identify the location of the feature files.
Q #30) What is the use of glue property under the Cucumber Options tag?
Answer: Glue property is used to let the Cucumber framework identify the location of step definition files.
Q #31) What is the maximum number of steps that are to be written within a scenario?
Answer: 3-4 steps.
Recommended Reading: Automation testing with Cucumber and Selenium

Most Frequently Asked Cucumber Interview Questions & Answers


1) What is Cucumber? What are the advantages of Cucumber?
Answer: Cucumber is a tool used to run automated acceptance tests created in a BDD format. One of the most
outstanding features of the tool is the ability to carry out plain-text functional descriptions (written in the language called
Gherkin) as automated tests.

The advantages of Cucumber are

 Its focus on end-user experience


 Cucumber tests are written in plain-text English so people with no or less technical skills can also write scenarios
 It allows us to involve business stakeholders who can’t easily read a code
 Allows quick and easy setup and execution
 High reusability of code in the tests
 It can be integrated with Selenium and other testing frameworks like JUnit & TestNG

2) What are the files needed in a Cucumber framework?


Answer: The files needed in a Cucumber framework are listed below:

Feature file – The feature file has an extension of .feature. It has single or multiple test scenarios described in plain text.
The tests are written with keywords like Then, When, Background, Scenario Outline, Feature, And, But, and so on. Thus it is
a file that maintains the features and their descriptions.

Step Definition file – This file has an extension of .java. It basically provides the mapping of the test scenario steps
described in the feature file to the automation code. Thus when Cucumber runs a step described in the feature file, it
searches the step definition file and executes the relevant functions that are mapped to that step.

TestRunner file – This file has an extension of .java. It links the step definition file and the feature file. It gives the user the
option to execute one or more than one feature file. It has the path of the step definition file and the feature file.

3) What are the different keywords used in feature file?


Answer: The different keywords used in the feature file are

 Feature
 Background
 Scenario
 Scenario Outline
 Given
 When
 Then
 And
 But

4) Explain Scenario Outline in the Cucumber framework?


Answer: A Scenario Outline is used to run a particular scenario with more than one data set in multiple combinations. A
feature file can have fewer lines if we take the help of a Scenario Outline. The data to be passed at runtime need not be
hardcoded in the feature file if we use Scenario Outline.

With Scenario Outline the runtime values are passed as parameters enclosed in <> in the feature file. The data set is
expressed in a tabular format separated with pipe delimiter starting with the Examples keyword.

Feature file with Scenario Outline implementation.

Feature: Admin Login Verification


Scenario Outline: Multiple Users Login Test
Given User navigates to Admin Login Page
When Page Title is Welcome to Admin
Then User inputs "<Name>" and "<EmployeeId>"
Examples:
| Name | EmployeeId |
| Adam | 3678 |
| Sam | 2589 |

5) Explain keyword Background in the Cucumber framework?


Answer: The keyword Background is used to describe a test step or a group of test steps that are common to every test
inside the feature file. A test having a Background executes before all the test scenarios in the feature file.

Thus a keyword Background is used to run a scenario as a precondition for other scenarios in the feature file.

Feature file with Background implementation

Feature: Admin Login Verification


Background: User Login Test
Given User navigates to Admin Login Page
When Page Title is Welcome to Admin
Scenario: New user addition by admin user
Given User navigates to New Member Page
Then Add New Member button should be visible
Scenario: User deletion by admin user
Given User navigates to Member Delete Page
Then Delete Member button should be visible
In the above example, we are testing the Admin Login Verification feature. We have two scenarios – New user addition by
admin user and User deletion by an admin user. The precondition to both these scenarios is defined with Background
scenario – User Login Test and it shall execute two times before each of the scenarios.

6) Explain keyword Examples in the Cucumber framework?


Answer: We can achieve a data-driven approach in Cucumber with the help of the Examples keyword. The Scenario
Outline in a feature file should be accompanied by the Examples part which consists of the multiple data set to be passed
at the runtime.

The Examples section in the feature file should have headings that match with the variables in the Scenario Outline
followed by (|) symbol. Each row below the heading represents a set of data. So if there are two rows after heading, the
test scenario shall run two times with the two different sets of data.

Feature file with Examples implementation

Feature: New User Registration


Scenario Outline: Registration Verification Test
Given User navigates to Registration Page
Then User inputs "<Firstname>" and "<Lastname>" and "<Email>"
Examples:
| Firstname | Lastname | Email |
| Rob | Smith | abc@gmail.com|
| Deu | Alfred | xyz@gmail.com|

7) Explain BDD?
Answer: BDD means Behavior Driven Development. In Behavior Driven Development, the tests are designed in plain
English and are created from a more end-user perspective and describe the application characteristics.

Behavior Driven Development framework increases collaboration and coordination among members in an agile team of
developers, testers, business analysts, product owners, customers, and other stakeholders. It does not require any
technical knowledge and is written in plain text and requires no technical clarity.

Behavior Driven Development framework like Cucumber helps to bridge any understanding gap between business
stakeholders and the developers. Some of the benefits of using Behavior Driven Development are listed below:

 Since all the team members and stakeholders contribute to the project development, it ensures maximum testing
coverage.
 Since the tests are designed in plain text, there is proper understanding and knowledge over the business
requirements.
 Test tools like Cucumber and SpecFlow in Behavior Driven Development help to automate scenarios.
 Behavior Driven Development helps to achieve reusability of code to a large extent.
 Data parameterization can be easily implemented in Behavior Driven Development.
 Behavior Driven Development allows easy integration with continuous integration tools like Jenkins.

8) Describe a feature file with an example?


Answer: A feature file is the starting of tests in Cucumber. All the test scenarios are elaborated here in plain simple text. It
may contain single or multiple test scenarios at a time. It is recommended to create a separate feature file for each
standalone feature.

If we are using an Eclipse IDE, a feature file can be created by selecting our project, then right-click and select
the New option. Next click on File. Then we have to provide the name of the file with .feature as an extension.

A feature file normally contains some keywords described in Gherkin language. Let us discuss some of them:

 Feature – Defines a particular feature that we will test.


 Description – This is not mandatory and it describes what the feature deals in.
 Scenario – Describes a particular scenario.
 Given – Describes the prerequisites of a test scenario.
 Then – Describes the expected outcome of the test.
 And – Describes some of the further conditions to be tested.

Feature file implementation.

Feature: Payment Verification


Description: Verify if the user can complete a payment
Scenario: Verify the credit card payment type
Given User navigates to Credit Card Payment Page
Then Proceed With Payment button should be enabled
And Credit card payment should be done.

9) Describe a step definition file with an example?


Answer: First of all we have created a feature file with the test scenarios. But the Cucumber is still unaware of which code
to be run for a particular scenario. This is determined by the step definition file which gives one to one mapping of each
scenario in the feature file to the function to be executed.

Thus a step definition file is a file with .java extension and contains all the methods in a class having annotations that
map them to the scenarios in the feature file. All the keywords used in the Feature file is added to the step definition file
in the form of annotations and then importing cucumber.api.java.en package.

Now let us create a step definition file for the Feature Payment Verification in the feature file discussed above.

Step Definition file implementation.

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.And;
public class PaymentVerification{

@Given ("^User navigates to Credit Card Payment Page$")


public void navigate_to_credit_card_payment (String url) {
System.out.println ("Url is : " + url);
}

@Then ("^Proceed With Payment button should be enabled$")


public void verify_payment_button_status () {
System.out.println ("Button is enabled ");
}

@And ("^Credit card payment should be done$")


public void verify_payment_status () {
System.out.println ("Credit card payment is successful");
}
}

10) How to achieve parameterization in the Cucumber framework?


Answer: We can achieve parameterization in Cucumber. This helps to pass multiple data sets at runtime in multiple
combinations. We can perform data parameterization in the following ways:

 With the help of keyword Examples.


 Without the help of keyword Examples.
The Scenario Outline in a feature file should be accompanied by the Examples part. This consists of the multiple data sets
to be passed at runtime.

The Examples section in the feature file should have headings that match with the variables in the Scenario Outline
followed by (|) symbol. Each row below the heading represents a set of data. So if there are two rows after heading, the
test scenario shall run two times with the two different sets of data.

Let us consider the feature file having the Feature New User Registration described previously. Next let us now create a
step definition file corresponding to that feature file.

Step Definition file implementation with Examples.

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
public class ParameterizationWithExample {
@Given ("^User navigates to Registration Page$")
public void navigate_to_registration () {
System.out.println ("Navigation to registration is done");
}

@Then ("^User inputs \"(.*)\" and \"(.*)\" and \"(.*)\"$")


public void user_input (String fname, String lname, String email){
System.out.println ("First name is: " + fname);
System.out.println ("Last name is: " + lname);
System.out.println ("Email is: " + email); }
}
In the above example, we have passed three values Firstname, Lastname and Email at the run time without requiring to
hardcode test data inside the step definition file. With the help of User inputs \”(.*)\” and \”(.*)\” and \”(.*)\ statement,
Cucumber understands that there are three runtime parameters. Also, three parameters are passed as arguments to
the user_input method.

Now let us see how to do data parameterization without Examples.

Feature file implementation.

Feature: Launch Software Testing Material application


Scenario: Software Testing Material launching URL
Given Navigate to “https://www.softwaretestingmaterial.com/”

In the above example, we have passed the URL directly within the Given statement in the feature file.

Step Definition code Implementation.

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
public class ParameterizationWithoutExample {
@Given ("^Navigate to \"([^\"]*)\"$")
public void navigate (String url) {
System.out.println ("URL is: " + url); }
}
In the above example, we have passed one value https://www.softwaretestingmaterial.com/ that executes at run time
without requiring to hardcode test data inside the step definition file. With the help of Navigate
to \”([^\”]*)\ statement, Cucumber understands that there is one runtime parameter. Also, this parameter is passed as
an argument to the navigate method.

11) How is the Options tag used in the Cucumber framework?


Answer: The Cucumber Options tag is a part of the TestRunner file and comes in the form of an annotation
called @CucumberOptions. It contains parameters like feature and glue. The feature parameter has the path of the
feature file and the glue parameter has the path of the step definition file.

Code Implementation of TestRunner file with Option tag.

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith (Cucumber.class)
@CucumberOptions (
features = "src/test/java/features ",
glue = {"stepDefinitions"}
)
public class TestRunner {
}
We have to import org.junit.runner.RunWith for the @RunWith annotation and cucumber.api.CucumberOptions for
the @CucumberOptions annotation.

12) What are some of the keywords used to build a scenario in Cucumber?
Answer: various keywords that are used in Cucumber for writing a scenario

 Given
 When
 Then
 And

13) Explain the purpose of keywords that are used for writing a scenario in
Cucumber?
Answer:

“Given” keyword is used to specify a precondition for the scenario.


“When” keyword is used to specify an operation to be performed.
“Then” keyword is used to specify the expected result of a performed action.
“And” keyword is used to join one or more statements together into a single statement.

14) Name any two build management tools that can be integrated with
Cucumber?
 Gradle
 Maven

15) Describe a TestRunner file with an example?


Answer: A TestRunner file contains a JUnit class. It contains the @RunWith and @CucumberOptions annotations. We
need to import org.junit.runner.RunWith and cucumber.api.CucumberOptions for the annotations @RunWith and
@CucumberOptions respectively.

The @CucumberOptions has parameters like features, glue, tags, plugin, and so on. The features parameter contains the
location of the feature file. The tags parameter is used to include or exclude a tagged scenario in a feature file in the
execution. If we provide the (~) before the tag name, we are simply excluding that scenario from the run.

The parameter plugin is used for Cucumber reports in various formats like HTML, JSON, and so on. The pretty, html:
test-output values in the plugin is used to generate an HTML report inside the test-output folder within the framework.
The parameter strict is used to verify whether any step is not included in the step definition file and
the dryRun parameter is used to validate if there is a proper mapping between the step definition file and the feature file.

Inside the JUnit class, we can add annotations like @BeforeClass and @AfterClass, to run a precondition or a
postcondition for a test. We have to import org.junit.BeforeClass and org.junit.AfterClass for the @BeforeClass and
@AfterClass annotations respectively.

Code Implementation of TestRunner file.

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.BeforeClass;
import org.junit.AfterClass;

@RunWith (Cucumber.class)
@CucumberOptions (
features = "src/test/java/features ",
glue = {"stepDefinitions"},
plugin = {"pretty", "html:test-output"},
strict = true,
dryRun = false,
tags = {"~@Smoke" , "@Payment"}
)
public class TestRunner {

@BeforeClass
public void before () {
System.out.println ("Executes before all tests"); }

@AfterClass
public void after () {
System.out.println ("Executes after all tests");
}
}

16) Can Cucumber be integrated with Selenium?


Answer: Yes we can integrate Cucumber with Selenium. First of all we need to download the Selenium-server-standalone
jar from the below link and add this to our project:

https://www.selenium.dev/downloads/

Next, we should navigate to the Maven repository with the below link:

https://mvnrepository.com/search?q=Cucumber

Then download the following Cucumber Jars listed below and add them to the Project:

 JUnit
 Gherkin
 Cucumber-JUnit
 Cucumber-Java
 Hemcrest-core
 Cucumber – reporting
 Cucumber – html
 Cucumber – core
 Cobertura – code coverage
 Cucumber – jvm –deps

Next we have to install the Cucumber Eclipse plugin for which we have to navigate to Install New Software from the Help
menu in Eclipse and then add the link: http://cucumber.github.io/cucumber-eclipse/update-site/ for installation.

Then we have to create a feature file with the test scenarios in a step by step approach in Gherkin language, a step
definition file for actual Selenium code implementation of the scenarios, and the test runner file to run the Cucumber
tests.

17) Which language is used in Cucumber?


Answer: The language that Cucumber understands is called Gherkin. It is a simple English representation of the
application behavior. It is used to define test cases. It is designed to be non-technical and human-readable, and
collectively describes use cases relating to a software system. It is a Business Readable, Domain Specific Language (DSL).

18) Define programming language that is used by Cucumber?


Answer: Cucumber tool provides support for numerous programming languages such as Java, .Net, Ruby, etc. It can also
be included with several tools such as Capybara, Selenium, etc.

19) What are hooks in the Cucumber framework?


Answer: A block of code tagged with hooks in Cucumber can run prior or post a scenario with the help of @Before and
@After annotations. Thus hooks help to control the flow of the program and optimize lines of code.

There may be scenarios that require certain preconditions to be executed like launching the application, establishing
database connection, configuring the test data, and so on. Also, there are certain post conditions to be executed like
terminating database connection, closing the browser, refreshing test data, application log out, and so on.

All these conditions are handled in Cucumber with the help of the hooks. The @Before hook executes before the actual
scenario and the @After hook executes after the actual scenario even if the test corresponding to the actual scenario fails.

We have to import cucumber.api.java.en.Before for the @Before annotation and import


cucumber.api.java.en.After for the @After annotation.
Code Implementation with hooks.

Feature file.

 Feature: Invoice Generation


 Scenario: Verify the invoice generates in pdf format
 Given User navigates to Invoice Page
 Then User should be able to open the invoice in pdf format
 Scenario: Verify the invoice fields
 Given User opens the invoice
 Then User should be able to see the payment amount in invoice

In the above feature file, we have included two scenarios.

Step definition file.

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.Before;
import cucumber.api.java.en.After;
public class InvoiceValidation {

@Given ("^User navigates to Invoice Page$")


public void navigate_to_invoice () {
System.out.println ("Navigation to Invoice Page");
}
@Then ("^User should be able to open the invoice in pdf format$")
public void open_invoice_pdf () {
System.out.println ("Invoice opened in pdf format ");
}
@Given ("^User opens the invoice$")
public void open_invoice () {
System.out.println ("Invoice is opened");
}
@Then ("^User should be able to see the payment amount in invoice$")
public void verify_payment_invoice () {
System.out.println ("Invoice contains payment amount");
}
@Before
public void precondition () {
System.out.println ("The method runs before all scenarios");
}
@After
public void postcondition () {
System.out.println ("The method runs after all scenarios ");
}
}
In the above example, since there are two scenarios, the test method precondition with @Before annotation and the test
method postcondition with @After annotation shall run twice.

20) How to comment on the Cucumber framework?


Answer: We can add comments in the Cucumber code. The comments are incorporated in code mostly for
documentation and not for including program logic. It makes the code easier to apprehend and to debug the errors. Also,
comments can be put at any point in the code.

Inside the feature file, the comments are added after the (#) symbol and the step definition contains comments after the
(//) symbol.

Feature file with comments.

 Feature: Customer verification


 # Scenario with customer
 Scenario: Verify customer details
 Given User navigates to Customer Information Page

Step definition file with comments

import cucumber.api.java.en.Given;
public class CustomerInformation {

@Given ("^User navigates to Customer Information Page$")


//method to map @Given scenario in feature file
public void navigate_to_customerInformation () {
System.out.println ("Customer Information Page is navigated");
}
}

21) How to use regular expressions in the Cucumber framework?


Answer: We can use regular expressions in the Cucumber framework inside the step definition file. The regular expression
can be used to combine two or more similar steps in the feature file within a test method in the step definition file. Also,
the regular expression is used for data parameterization in Cucumber as the Feature New User Registration in the
feature file described previously.

Feature file implementation.

 Feature: Student Study Schedule


 Description: Verify student study schedule
 Scenario: Verify hours spent on science subjects
 Given Student studies Chemistry on Tuesday
 Given Student studies Mathematics on Tuesday
 Given Student has thirty minutes recess

Step definition file with regular expression.

import cucumber.api.java.en.Given;
public class StudentSchedule {

@Given ("^Student studies ([^\"]*) on Tuesday$")


public void student_Tuesday_schedule (String subject) {
if (subject.equals ("Chemistry")){
System.out.println ("Student studies Chemistry on Tuesday");
} else {
System.out.println ("Student studies Mathematics on Tuesday");
}
}
@Given ("^Student has thirty minutes recess$")
public void student_recess () {
System.out.println ("Student recess time is thirty minutes");
}
}
In the above example, we have computed the subject’s Chemistry and Mathematics inside one
method student_Tuesday_schedule without requiring to hardcode test data inside the step definition file. With the help
of Student studies ([^\”]*) statement we have combined two Given (Student studies Chemistry on Tuesday and
Student studies Mathematics on Tuesday) statements inside one method.

22) How to skip tests in the Cucumber framework?


Answer: We can skip tests in the Cucumber framework with the help of the tags concept which comes under
CucumberOptions in the TestRunner file. We can tag a scenario in the feature file with help @<<tagname>> keyword.

A scenario inside the feature file can have one or multiple tags. With the help of the tagging, we can segregate test
scenarios. We can mention these tagged scenarios inside the tags parameter under @CucumberOptions in the
TestRunner file. To skip tests in Cucumber we have to pass the ~<<tagname>> expression within the tags parameter.

Feature file implementation with tags.

 Feature: Insurance Details


 @Information
 Scenario: To verify Insurance information
 Given User is on the Insurance Information Page
 @Premium
 Scenario: To verify Insurance premium information
 Given User is on the Insurance Premium Page

Code Implementation of TestRunner file to skip test.

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith (Cucumber.class)
@CucumberOptions (
features = "src/test/java/features ",
glue = {"stepDefinitions"},
tags = {"~@Premium"}
)
public class TestRunner {
}
In the above example, since there are two scenarios with tags @Information and @Premium, the test scenario with
@Information shall run and the test scenario @Premium shall skip since the parameter tags = {“~@Premium”} has been
added in the TestRunner file under @CucumberOptions.

23) How to set priority to tests in the Cucumber framework?


Answer: We can set priority to tests in Cucumber to determine the order of execution. We use Cucumber hooks to control
the flow of execution. But this can be modified with the help of the order.

Let us take a step definition file having two test methods with @Before annotations. In order to control the sequence of
their execution, we can use @Before (order = int) statement. This ensures that the test methods are executed in an
incremental manner. This means the test method having order = 1 shall execute before the method having order = 2.

Thus we can set priority to a test method such that the method having lower order shall be executed first followed by the
test method having higher order.

Step definition file implementation.

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Before;
public class PriorityTest {

@Given ("^User navigates to Reorder page$")


public void navigate_reorder () {
System.out.println ("Reorder page is navigated");
}
@Before (order = 2)
public void precondition1 () {
System.out.println ("The precondition1 is to be executed");
}
@Before (order = 1)
public void precondition2 () {
System.out.println ("The precondition2 is to be executed");
}
}
In the above example, the test method precondition2 [having order = 1] shall be executed first, followed by the test
method precondition1 [having order = 2]. Finally the test method navigate_reorder will be executed.

24) How to run a precondition test for a scenario in the Cucumber framework?
Answer: We can run a precondition test for a scenario in Cucumber. A scenario inside the feature file can have one or
multiple tags. With the help of the tagging we can segregate test scenarios.

A block of code tagged with hooks in Cucumber can run prior to a scenario with the help of @Before annotation. Thus
tagged hooks help to control the flow of the program. There may be a scenario that requires a certain precondition to be
executed.

This kind of situation is handled in Cucumber with the help of the tagged hooks. The @Before (“Scenario
Tagname”) expression is used to execute a certain precondition for a scenario. We have to import
cucumber.api.java.en.Before for the @Before annotation.

Feature file implementation with hooked tags on scenarios.

 Feature: Buy Insurance


 @Dental
 Scenario: To verify buying of Dental Insurance
 Given User is on the Dental Insurance Page
 @Car
 Scenario: To verify buying of Car Insurance
 Given User is on the Car Insurance Page
 @Accidental
 Scenario: To verify buying of Accidental Insurance
 Given User is on the Accidental Insurance Page

In the above feature file, we have included three scenarios.


Step definition file implementation.

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Before;
public class Insurance {
@Given ("^User is on the Dental Insurance Page$")
public void navigate_dental_Insurance () {
System.out.println ("Navigation to Dental Insurance Page");
}
@Given ("^User is on the Car Insurance Page$")
public void navigate_car_Insurance () {
System.out.println ("Navigation to Car Insurance Page");
}
@Given ("^User is on the Accidental Insurance Page$")
public void navigate_accidental_Insurance () {
System.out.println ("Navigation to Accidental Insurance Page");
}
@Before ("@Car")
public void preconditionCar () {
System.out.println ("Method runs before car insurance scenario");
}
@Before ("@Dental")
public void preconditionDental () {
System.out.println ("Method runs before dental insurance scenario");
}
@Before ("@Accidental")
public void preconditionAccidental () {
System.out.println ("Method runs before accidental insurance"); }
}
In the above example, the test method preconditionCar [having @Before (“@Car”)] shall be executed before
the navigate_car_Insurance method since it is tagged with @Car in the feature file. We can say that
the preconditionCar method is just like a precondition to the navigate_car_Insurance method.

The test method preconditionDental [having @Before (“@Dental”)] shall be executed before
the navigate_dental_Insurance method since it is tagged with @Dental in the feature file. We can say that
the preconditionDental method is just like a precondition to the navigate_dental_Insurance method.

The test method preconditionAccidental [having @Before (“@Accidental”)] shall be executed before
the navigate_accidental_Insurance method since it is tagged with @Accidental in the feature file. We can say that
the preconditionAccidental method is just like a precondition to the navigate_accidental_Insurance method.

25) How to run a selected test from a group of tests in Cucumber framework?
Answer: We can run a selected test from a group of tests in the Cucumber framework with the help of tags concept. This
comes under the @CucumberOptions in the TestRunner file. We can tag a scenario in the feature file with
help @<<tagname>> keyword.

A scenario inside the feature file can have one or multiple tags. With the help of the tagging, we can segregate test
scenarios. We can mention these tagged scenarios inside the tags parameter under @CucumberOptions in the
TestRunner file. To run a selected test in Cucumber we have to pass the <<tagname>> value and to exclude from
running we have to pass the <<~tagname>> value within the tags parameter.

Let us consider the Feature: Buy Insurance in the feature file described previously.

Code Implementation of TestRunner file to run selected test.

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith (Cucumber.class)
@CucumberOptions (
features = "src/test/java/features ",
glue = {"stepDefinitions"},
tags = {"@Dental", "@Car", "~Accidental" }
)
public class TestRunner {
}
In the above example, there are three scenarios, but only the test scenarios with @Dental, @Car tags shall run and the
test scenario with @Accidental tag shall not be included in the execution.

26) Why is the property glue used in the Cucumber Options tag?
Answer: The property glue is used with the Cucumber Options tag which is a part of the TestRunner file. It takes the
location or path of the step definition file.
Code Implementation of TestRunner file with glue.

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith (Cucumber.class)
@CucumberOptions (
features = "src/test/java/features ",
glue = {"stepDefinitions"}
)
public class TestRunner {
}

27) What is a test harness?


Answer: A test harness is a framework that contains test cases, test data, certain parameters and configurations, collects
test results and records them.

28) How to generate reports with Cucumber?


We can generate the output/report of the cucumber using different cucumber commands.

>cucumber adding.feature –format HTML


>cucumber adding.feature –out report.html
>cucumber adding.feature –format pretty

The report file will be stored in the project folder itself.

How to use Message as a Parameter in TestNG Asserts?


In the above example, you may notice that an AssertionError is thrown by Java which is quite complete in its own form. But, in
TestNG asserts, we can mention a message as well in the parameter that will be displayed when the assertion fails along with the
assertion error. So, as a slight modification to the syntax, this will work as a third parameter making syntax as follows:

Assert.Method(actual, expected, message)


The parameter as you see contains three values:

 Actual: The actual value that the tester gets like if the tester's assertion is on the title of the page then what was the actual
title of the page goes here.
 Expected: The value that you expect like if the tester's assertion is on the title of the page then what value of title do you
expect goes here.
 Message: A string message to display only in case of an error when the assert fails.

Let's explore the assert in TestNG by writing a simple test case.

The below-given code is exactly the same code as mentioned in the previous section. Therefore, I have mentioned just
the OpenBrowser function since the changes are made only in this part of the code. In the following code, we have used "Titles of
the website do not match" as the message parameter which is expected to be seen on the console if the assertion fails.

public void OpenBrowser() {

driver.get("https://www.demoqa.com");

Reporter.log("The website used was DemoQA for this test", true);


String expectedTitle = "Free QA Automation Tools For Everyone";
String originalTitle = driver.getTitle();
Assert.assertEquals(originalTitle, expectedTitle, "Titles of the website do not match");
}

You might also like