Selenium Interview Questions and Answers by Advanto
Selenium Interview Questions and Answers by Advanto
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.
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:
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
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.
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.
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;
@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:
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
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 #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.
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.,
Read the detailed explanation on the challenges and limitations of Selenium WebDriver
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:
Subjective Validation
New Functionalities
Strategic Development
User Experience
Complex Functionality
Quality Control
Low return on investment
Installation and setup testing
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.
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.
Selenium is a set of different software tools. Each tool has a different approach in supporting web based automation
testing.
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.
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.
In simple words, it is used to distribute your test execution on multiple platforms and environments concurrently.
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
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
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
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.
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.
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.
Hard Assert: Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues
with next @Test
setSpeed(): It set up speed that will apply a delay time before every Selenium operation.
sleep(): It set up wait only for once when called in our Selenium script.
Note: setSpeed method is applicable to Selenium IDE and Selenium RC. We cannot use setSpeed in Selenium WebDriver.
Note: If you use geckodriver with Selenium, you must upgrade to Selenium 3.3. Here we have to set the property as follows
instead of creating
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
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.
A stale element reference exception is thrown in one of two cases, the first being more common than the second.
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
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.
Practical example
Practical example
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
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
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);
}
}
HTML:
driver.findElement(By.id("form_1")).submit();
Alternatively, you can use click method on the element which does form submission
driver.findElement(By.xpath("xpath")).sendKeys(Keys.ENTER);
Thread.sleep(5000)
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”)
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
driver.getCurrentUrl();
driver.manage().window().maximize();
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
-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.
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
1. isDisplayed()
2. isSelected()
3. isEnabled()
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.
Practical Example.
(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
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:
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
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)
1. titleIs() – The expected condition waits for a page with a specific title.
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.
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
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.
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.
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());
}
Practical Example.
Practical Example
108. How to run Selenium WebDriver Test from the command line?
Run Java Program using Command Prompt
Run TestNG using Command Prompt
driver.switchTo().frame();
We use JDBC Driver to connect the Database in Selenium (While using Java Programming Language).
Practical Example
Practical Example
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
Practical Example
Practical Example
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.
Some of the continuous integration tools are Jenkins, TeamCity, Bamboo, Travis, Circle Ci, Bitbucket.
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
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.
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.
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
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.
Practical Example
@DataProvider(name="getData")
public Object[][] getData(){
//Object [][] data = new Object [rowCount][colCount];
Object [][] data = new Object [2][2];
data[1][0] = "SecondUid";
data[1][1] = "SecondPWD";
return data;
}
Practical Example
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.
There are different types of test automation frameworks and the most common ones are:
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.
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.
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?
Table of Contents
#1. ABSTRACTION
Abstraction is the methodology of hiding the implementation of internal details and showing the functionality to the
users.
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.
In Java, abstraction is achieved by interfaces and abstract classes. Using interfaces, we can achieve 100% abstraction.
#2. INTERFACE
Basic statement we all know in Selenium is WebDriver driver = new FirefoxDriver();
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.
#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.
#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.
A class having multiple methods with same name but different parameters is called Method Overloading
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 .
#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.
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)
I focus on the test cases which should be executed in a repetitive manner such as regression test cases, smoke and sanity
test cases
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.
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:
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.
@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.
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
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.
We could set the parameter using the below syntax in the testng.xml file.
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.
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
Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues with next @Test
Practical Example
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
We use priority attribute to the @Test annotations. In case priority is not set then the test scripts execute in alphabetical
order.
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.
data[1][0] = "SecondUid";
data[1][1] = "SecondPWD";
return data;
}
Practical Example
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.
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
we can use “parallel” attribute in testng.xml to accomplish parallel test execution in TestNG
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?
<classes>
<class name="TestCaseName">
<methods>
<exclude name="TestMethodNameToExclude"/>
</methods>
</class>
</classes>
19. How to exclude a particular test group from a test case execution?
<groups>
<run>
<exclude name="TestGroupNameToExclude"/>
</run>
</groups>
Practical Example
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?
Once SkipException() thrown, remaining part of that test method will not be executed and control will goes directly to
next test method execution.
To ignore the test case we use the parameter enabled = false to the @Test annotation.
@Test(enabled = false)
Practical Example
24. What are the different ways to produce reports for TestNG results?
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.
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.
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\*
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
The threadPoolSize attribute tells to form a thread pool to run the test method through multiple threads.
@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.
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.
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.
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.
Download PDF
CI/CD DevOps
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.
Jenkins
CircleCI
Bamboo
Team City
Codefresh
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.
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.
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.
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.
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.
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.
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.
The following are the differences between Docker images and containers:
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.
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.
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
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.
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?
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.
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.
To help you establish an efficient pipeline for CI/CD, here are some best practices:
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.
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.
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)
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.
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.
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.
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.
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.
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."
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.
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
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
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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. }
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.
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
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.
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$")
driver.manage().window().maximize();
driver.get("www.facebook.com");
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"})
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.
Feature
Background
Scenario
Scenario Outline
Given
When
Then
And
But
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.
Thus a keyword Background is used to run a scenario as a precondition for other scenarios in the feature file.
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.
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.
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:
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.
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.And;
public class PaymentVerification{
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.
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");
}
In the above example, we have passed the URL directly within the Given statement in the feature file.
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.
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:
14) Name any two build management tools that can be integrated with
Cucumber?
Gradle
Maven
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.
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");
}
}
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.
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.
Feature 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 {
Inside the feature file, the comments are added after the (#) symbol and the step definition contains comments after the
(//) symbol.
import cucumber.api.java.en.Given;
public class CustomerInformation {
import cucumber.api.java.en.Given;
public class StudentSchedule {
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.
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.
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.
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Before;
public class PriorityTest {
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.
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.
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 {
}
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.
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.
driver.get("https://www.demoqa.com");