Automation Related Topics
Automation Related Topics
1. POM.xml (Maven)
2. Test NG
3. Maven
4. POM.xml
5. Zephyr
6. Collections
7. Oops concepts
Qns :
1. What are the different types of automation framework with which data’s can be passed to your
test cases.
2. How is your Automation Script connected to Jenkins , and how is it run
3. How is Automation test cases linked to JIRA test cases
4. How is the screenshots of the failures captured
5. How is the Final Reports of the Automation Job sent via Jenkins
6. Database testing via Automation
7. Can we run TestNG xml via a non maven project or only via maven project ?
if(browser == "chrome") {
driver = new chromedriver;
}
TestNG, Junit both are automation framework. TestNG overcomes the disadvantages of JUnit and is
designed to make end-to-end testing easy.
Uses :
1. Proper reports can be made using Test NG (how many test cases failed , passed etc)
2. Specific test cases (methods) can be run.
3. Also supports running only failed test cases from previous run. Failed tc are stored in “testing-
failed.xml” in output folder which is then run specifically after fixing the issues.
Generate the report in a proper format including a number of test cases runs, the number of
test cases passed, the number of test cases failed, and the number of test cases skipped.
Multiple test cases can be grouped more easily by converting them into testng.xml file. In which
you can make priorities which test case should be executed first.
The same test case can be executed multiple times without loops just by using keyword called
'invocation count.'
Using testng, you can execute multiple test cases on multiple browsers, i.e., cross browser
testing.
The testing framework can be easily integrated with tools like Maven, Jenkins, etc.
Annotations used in the testing are very easy to understand ex: @BeforeMethod,
@AfterMethod, @BeforeTest, @AfterTest
WebDriver has no native mechanism for generating reports. TestNG can generate the report in a
readable format like the one shown below.
TestNG simplifies the way the tests are coded. There is no more need for a static main method
in our tests. The sequence of actions is regulated by easy-to-understand annotations that do not
require methods to be static.
Uncaught exceptions are automatically handled by TestNG without terminating the test
prematurely. These exceptions are reported as failed steps in the report.
2.2 Annotations :
@BeforeTest - methods under this annotation will be executed prior to the first test case in the TestNG
file.
@AfterTest - methods under this annotation will be executed after all test cases in the TestNG file are
executed.
@BeforeTest
@Test(priority = 1)
@Test(priority = 2)
@Test(priority = 3)
@AfterTest
--------------------------------------------------------------------------------------------
@BeforeMethod - methods under this annotation will be executed prior to each method in each test
case.
@AfterMethod - methods under this annotation will be executed after each method in each test case.
@BeforeMethod
@Test(priority = 1)
@AfterTest
@BeforeMethod
@Test(priority = 2)
@AfterTest
@BeforeSuite: The annotated method will be run before all tests in this suite have run.
@AfterSuite: The annotated method will be run after all tests in this suite have run.
@BeforeTest: The annotated method will be run before any test method belonging to the
classes inside the tag is run.
@AfterTest: The annotated method will be run after all the test methods belonging to the
classes inside the tag have run.
@BeforeGroups: The list of groups that this configuration method will run before. This method
is guaranteed to run shortly before the first test method that belongs to any of these groups is
invoked.
@AfterGroups: The list of groups that this configuration method will run after. This method is
guaranteed to run shortly after the last test method that belongs to any of these groups is
invoked.
@BeforeClass: The annotated method will be run before the first test method in the current
class is invoked.
@AfterClass: The annotated method will be run after all the test methods in the current class
have been run.
@BeforeMethod: The annotated method will be run before each test method.
@AfterMethod: The annotated method will be run after each test method.
TestNG is a Testing framework that covers different types of test designs like unit, functional, end to
end, UI and integration test.
Test NG Xml :
Include – This tell us the list of group names to be included in the run
Exclude – This tells us the list of group names that has to be excluded in the run
The below XML runs only the test cases in the “BVT” group
<groups>
<run>
</run>
</groups>
Suite : <suite> tag, holds a logical name. TestNG generates execution reports, information’s to these
TestNG reports are defined by the suite (Test NG report name)
Test : <test name="Guru 99 Smoke Test Demo">, this test name contains informations of the TestNG
generated reports like PASS, FAIL, UNEXECUTED, Time taken to execute, group informations etc.
<suite name="Suite">
<groups>
<run>
</run>
</groups>
<classes>
<class
name="com.group.guru99.TC_Class1" />
</classes>
</test>
</suite>
The above XML runs all the test cases inside the above mentioned class which has the group name as
mentioned above.
Also in the Test NG.xml we can specifically mention the list of method names that has to be run
Eg :
What is Maven?
Maven is a powerful project / build management tool, based on the concept of a POM (Project Object
Model) that includes project information and configuration information for Maven such as construction
directory, source directory, dependency, test source directory, Goals, plugins, etc.
Selenium WebDriver is great for browser automation. But, when using it for testing and building a test
framework, it feels underpowered. Integrating Maven with Selenium provides following benefits
Apache Maven provides support for managing the full lifecycle of a test project.
Maven is used to define project structure, dependencies, build, and test management.
Using pom.xml(Maven) you can configure dependencies needed for building testing and running code.
Maven automatically downloads the necessary files from the repository while building the project.
POM.XML
All the contents in the POM.XML will be build by the Maven, say all the dependencies available in the
POM.XML will be added to the build path at the time of build, with the help of Maven. Maven is used
to fetch the latest dependencies and will add those jar files to your build path. So that these can be
utilized by our code.
In Pom.xml add the Selenium, Maven, TestNG, Junit, Screenshot dependencies etc to pom.xml in the
<project> node:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.45.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>test</scope>
</dependency>
</dependencies>
Using the Build a Maven Project option, Jenkins supports building and testing Maven projects.
So in eclipse, if you create a maven project, this can be easily added into Jenkins.
If we don’t mention any priority, testng will execute the @Test methods based on alphabetical order of
their method names irrespective of their place of implementation in the code.
If multiple methods has same priority, then it will execute based on alphabetical order.
The test case with the lowest number will be run first. Followed by the 2 nd least number. This is how
priority works. It is case sensitive.
When we run an automation script, it will be run in a browser. Each time a browser is opened it is
handled in a session. When we run multiple automation script, while another session or browser is
already running, the new script should not make the old session to stop. Hence session handling is
required
In selenium by default, each time when we write the below piece of code, automatically a session is
given to this. A sessionid is already described as part of the chromedriver() implementation. Hence even
if we call the driver multiple times, each sessions will go on parallelly without getting interrupted.
Tread-count ------------ Denotes the maximum number of session or browser that runs at a time
method -------------- it executes all the methods inside the mentioned class parallelly.
test---------------- it executes all the test cases metioned inside <test> tag in the testing.xml parallely.
Classes---------------- then it executes all the classes present inside a java class parallely.
<test name="flipkart">
<classes>
<class name="com.suite1.Flipkart"/>
</classes>
</test>
<test name="Myntra">
<classes>
<class name="com.suite2.SnapDeal"/>
</classes>
</test>
</suite>
In the above testing.xml, since the parallel = “tests”. All the test cases present inside the <test> tag in
the testNG.xml would be run parallel.
Note : Any method above which @Test is indiciated is called a test case
Listener - Listener is defined as interface that modifies the default TestNG's behavior.
TestNG has multiple listeners. Nothing but multiple interfaces. Each of these interfaces will contain
multiple methods.
The main purpose of using Listener is to generate customised logs or customize TestNG reports in
Selenium Webdriver.
1. IAnnotationTransformer ,
2. IAnnotationTransformer2 ,
3. IConfigurable ,
4. IConfigurationListener ,
5. IExecutionListener,
6. IHookable ,
7. IInvokedMethodListener ,
8. IInvokedMethodListener2 ,
9. IMethodInterceptor ,
10. IReporter,
11. ISuiteListener,
12. ITestListener .
Above Interfaces are called TestNG Listeners. These interfaces are used in selenium to generate logs or
customize the TestNG reports.
ITestListener has following methods (These methods in ITestListener will be implemented after each
tests)
Quick Steps :
1. Create a class and implement the required listener interface. This is a base Listener class
2. Create new classes and link the base listener class created in step1 to the required new classes
Or
Add the base listener class which we created in step 1 to the TestNG.XML. This will be applied to all the
methods in the test suite.
Detailed Steps :
extends is for when you're inheriting from a base class (i.e. extending its functionality).
Step 1 : Create a Class and implement “ITestListener” interface. All empty methods are displayed below,
which are inherited from “ITestListener” package.
package Listener_Demo;
import org.testng.ITestContext ;
import org.testng.ITestListener ;
import org.testng.ITestResult ;
@Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
@Override
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
@Override
public void onTestFailure(ITestResult arg0) {
@Override
public void onTestSkipped(ITestResult arg0) {
@Override
public void onTestStart(ITestResult arg0) {
@Override
public void onTestSuccess(ITestResult arg0) {
}
}
Step 2 : Pass on whatever content you want in the above empty methods
package Listener_Demo;
import org.testng.ITestContext ;
import org.testng.ITestListener ;
import org.testng.ITestResult ;
@Override
public void onFinish(ITestContext arg0) {
driver.get("http://demo.guru99.com/V4/");
driver.findElement(By.name("uid")).sendKeys("mngr34926");
driver.findElement(By.name("password")).sendKeys("amUpenu");
driver.findElement(By.name("btnLogin")).click()
@Override
public void onStart(ITestContext arg0) {
System.out.println("This method to test fail");
Assert.assertTrue(false);
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
@Override
public void onTestFailure(ITestResult arg0) {
@Override
public void onTestSkipped(ITestResult arg0) {
@Override
public void onTestStart(ITestResult arg0) {
@Override
public void onTestSuccess(ITestResult arg0) {
How do I let TestNG know that I have such a listener which it should invoke when it is
executing my tests?
There are essentially two ways of adding up a listener to a particular class.
1st Way : Adding @Listener(PackageName.ListenerClassName) on top of all the classes, this is a tedius
way. This is not the best approach as we have to modify all the classes one by one.
@Listeners(PackageName.ListenerClassName)
//eg : @Listeners(Listener_Demo.ListenerTest)
public class TestListener23545 {
2nd way (best approach) : Adding Listener in the TestNG.xml. This would implement listener
Listeners are required to generate logs or customize TestNG reports in Selenium Webdriver.
There are many types of listeners and can be used as per requirements.
Listeners are interfaces used in selenium web driver script
Demonstrated the use of Listener in Selenium
Implemented the Listeners for multiple classes
Run the TestNG.XML which we want to run. Inorder to create TestNG.XML, just choose the necessary
user created classes –> Right Click and choose TestNG -> Convert to TestNG -> Type the necessary
contents of the testng.xml and click finish.
Or else, while creating the class itself, we should have created a TestNG class.
“Test-output” folder – This folder contains the testNG.xml as well as the failedTestNG.xml as well.
Once the tests are run. Refesh the project and the package. Now a folder named “test-output” would be
displayed. Expand this “test-output” folder and “testng-failed.xml” would be displayed.
i.e,
Summary:
TestNG is Automation Testing Framework which is inspired from the Junit and contains different
annotations.
TestNG generates the reports in its standard report,which contains the following things:
Multiple test cases can be grouped easily and executed them by converting test classes into
testing suite file.
TestNG can be easily integrated with other third-party tools. It provides different features like
assigning the priority to the test cases, execution of same test case multiple times using
invocation count.
If any of the test case fails while executing multiple test cases, you can execute that specific test
case separately.
The static method "log" of Reporter class can be used to store logging information which is
present in org.testng.
Reporter.log(“the intended message”, true) - Parameter true is used to display the logs in the
console. Other wise, the logs will only be displayed in the testng reports.
Selenium web driver is used for automating the web-application, but it won't generate any reports.
When you execute testng.xml file, and refresh the project. You will get test-output folder in that
folder.
Right click on the emailable-report.html and select the option. Open with the web browser.
Method-1 : emailable-report.html
3. Contains just summarized information’s. Like number of passes and failures and unexecuted and
time taken.
Method-2 : index.html
1. contains indepth informations such as error, groups, time, reporter logs, testng XML
files.
2. Go to “test-output” folder and refresh it and then Right click on the index.html
3. Select option open with web browser option. It will display the result in the following
order.
For implementing a reporting class, the class has to implement an org.testng.IReporter interface.
“Report” is a class in “IReporter” interface. And “log” is a method inside “Report” class. This method
“log” is a static method, hence we are using it directly without creating any object.
org.testng.IReporter
public class Atest {
Public void Btest() {
Reporter.log(“dsgsd”);
}
}
The logs would also be present. The list of logs that got executed for each methods. This will be easy for
debugging.
1. ITestListener
package testNGReport.realTimeReport;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
@Override
public void onStart(ITestContext arg0) {
System.out.println("Start Of Execution(TEST)->"+arg0.getName());
@Override
public void onTestStart(ITestResult arg0) {
System.out.println("Test Started->"+arg0.getName());
:
:
@Listeners(RealGuru99TimeReport.class)
public class TestGuru99RealReport {
@Test
public void testRealReportOne(){
Assert.assertTrue(true);
}
@Test
public void testRealReportTwo(){
Assert.assertTrue(false);
}
2. IReporter
The coding part is bit tough, but is easier to implement only (So refer the https://www.guru99.com/pdf-
emails-and-screenshot-of-test-reports-in-selenium.html)
2. Take Screenshots ONLY on Errors. Link to screenshots in PDF (implement inside base listener)
3. Send Email of the PDF (implemented in a method which is executed after complete suite is
run)
Create a “JypersionListener” class, and implement the code for taking screenshot and attaching the link
to screenshot in the pdf inside the “OnTestFailure method” inside this Base listener class.
Note : JypersionListener is customer listener class which is used for taking screenshot and adding the
link to screenshot.
Now implement a method that has to be executed once all the test cases are run. That is @AfterSuite
method has to be created which contains the code for sending report PDF via email
@AfterSuite
public void tearDown(){
:
:
:
: <<Content not over fully, so refer the above link for full content
}
13.Page Object Model (POM) & Page Factory: Selenium WebDriver Tutorial
Page Object Model (POM) is a design pattern, popularly used in test automation that creates Object
Repository for web UI elements.
Page Factory is an inbuilt Page Object Model concept for Selenium WebDriver but it is very optimized.
@FindBy to find WebElement. PageFactory.initElements is needed to initialize all webelements on the
page object class.
We use Page Factory pattern to initialize web elements which are defined in Page Objects.
We should initialize page objects using initElements() method from PageFactory Class as below, Once we
call initElements() method, all elements will get initialized. PageFactory.initElements() static method
takes the driver instance of the given class and the class type, and returns a Page Object with its fields
fully initialized.
We create this as a constructor , so that whenever an object of this page object class is created, all the
webelements would be initialized.
AjaxElementLocatorFactory –
One of the key advantages of using Page Factory pattern is AjaxElementLocatorFactory Class.
It is working on lazy loading concept, i.e. a timeout for a WebElement will be assigned to the Object
page class with the help of AjaxElementLocatorFactory .
(Note : Instead of this you can use any other types of wait. Explicity wait or implicit wait)
Summary
To pass multiple data to the application at runtime, we need to parameterize our test scripts.
If for a given test, parameters is available at both the suite level, and the test level in the testNG.xml,
then preference would be given to the parameters present at the test level in the testNG.xml
The parameter variable name “author”, “searchkey” mentioned in the testNG.xml should be passed as
parameters for our method. The value for these variables would be fetched from the testNG.xml
@Test
@Parameters({"author","searchKey"})
public void testParameterWithXML( @Optional("Abc") String author,String
searchKey){
//content…
}
@Optional – If there is no value present for any variable in the testNG.xml, then the value mentioned in
the @Optional will be used for the variable for which no value is given in the xml.
Limitations :
1. We can’t use multiple different values for these parameters. Only 1 value mentioned in
the testNG.xml will be used throughout. For this we need to use “DataProviders”.
If we want to run a test case with multiple sets of data, then “Dataproviders” are used. A same test
case would be run with multiple sets of data.
@Parameters annotation is easy but to test with multiple sets of data we need to use Data Provider.
Data provider returns a two-dimensional JAVA object to the test method and the test method, will
invoke M times in a M*N type of object array. For example, if the DataProvider returns an array of 2*3
objects, the corresponding testcase will be invoked 2 times with 3 parameters each time.
@Test(dataProvider="SearchProvider")
public void testMethod(String author,String searchKey) {
//content
}
/**
* @return Object[][] where first column contains 'author'
* and second column contains 'searchKey'
*/
@DataProvider(name="SearchProvider")
public Object[][] getDataFromDataprovider(){
return new Object[][]
{
{ "Guru99", "India" },
{ "Krishna", "UK" },
{ "Bhupesh", "USA" }
};
Object array size is 3*2. The method will be run 3 times, with the values for the 2 parameters “author”
and “Search key” picked from each row of the dataprovider method.
Eg: 1st time when the above “testmethod” is run values for the 2 parameters mentioned in the
“testmethod” will be { "Guru99", "India" }.
2nd time when the above “testmethod” is run values for the 2 parameters mentioned in the
“testmethod” will be { "Krishna", "UK" }.
3rd time when the above “testmethod” is run values for the 2 parameters mentioned in the
“testmethod” will be { "Bhupesh", "USA" }
If we want to call this data provider in different class, then make this data provider method as “Static”.
Then mention this class name where dataprovider object is implemented in other classes.
DataproviderClass.java (This is a common class containing the dataproviders and is a static method)
package parameters;
import org.testng.annotations.DataProvider;
public class DataproviderClass {
@DataProvider(name="SearchProvider")
public static Object[][] getDataFromDataprovider(){
return new Object[][] {
{ "Guru99", "India" },
{ "Krishna", "UK" },
{ "Bhupesh", "USA" }
};
}}
Now we want to implement above data providers in a different class for a different method or test case,
Public class workingTest {
@Test(dataProvider="SearchProvider",dataProviderClass=DataproviderClass.class
)
public void testMethod(String author,String searchKey) {
}
}
The same logic as mentioned in the above (data provider present inside the same class) will happen
now, and the 3 parameters present in the data provider will be passed on to our “testMethod” 3 times,
with different values.
14.1 Method – We can specify multiple set of values to be used as parameters for different
methods.
@Test(dataProvider="SearchProvider")
public void testMethodA(String author,String searchKey) {
If the method name is “testMethodA”, the first set of object parameters would be used. Or else 2nd set
of parameter values. We can use multiple else if’s as well.
14.2 ITestContext- It can use to create different parameters for test cases based on groups.
If value of group is A, a particular data set is returned (in below eg, 1st set of para would be run)
If value of group is B, another data set is returned (in below eg, 2nd set of para would be run)
@Test(dataProvider="SearchProvider",groups="A")
public void testMethodA(String author,String searchKey) {
@Test(dataProvider="SearchProvider",groups="B")
public void testMethodB(String searchKey){
// 2nd set of parameters groupArray would be used
}
TestNG.XMl
<test name="example1">
<groups>
<run>
<include name="A" />
</run>
</groups>
<classes>
<class
name="parameters.ParameterByITestContextInDataprovider" />
</classes>
</test>
<test name="example2">
<groups>
<run>
<include name="B" />
</run>
</groups>
<classes>
<class
name="parameters.ParameterByITestContextInDataprovider" />
</classes>
</test>
</suite>
15.Read & Write Data from Excel File in Selenium Webdriver: POI & JXL
To read or write an Excel,Apache provides a very famous library POI. This library is capable enough to
read and write both XLS and XLSX file format of Excel.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
Or you can simply download the latest version POI jars and unzip it and add these all jars to the class
path of your project.
Following is a list of different Java Interfaces and classes in POI for reading XLS and XLSX file-
//Getting the cell value of the respective cell in that row and getting its value as string
row.getCell(j).getStringCellValue();
Qns for me :
The browser name is written inside POM.xml, inside <gridbrowser> or <browsername> tag. Then in our
test, we try to fetch the value stored for this browser tag from the POM.XML. And then try to create a
driver based on the value of this string.
<<Tbd>
Step 3) Send the query to database using execute query and store the results in the ResultSet object.
Java provides lots of built-in methods to process the SQL Output using the ResultSet Object
Results from the executed query are stored in the ResultSet Object.
Java provides loads of advance methods to process the results. Few of the methods are listed below
Package htmldriver;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnector {
public static void main(String[] args) throws
ClassNotFoundException, SQLException {
//Database Username
String username = "root";
//Database Password
String password = "guru99";
//Query to Execute
String query = "select * from employee;";
//Load mysql jdbc driver
Class.forName("com.mysql.jdbc.Driver");
//Create Connection to DB
Connection con =
DriverManager.getConnection(dbUrl,username,password);
Note : Inorder to capture screenshots on exceptions throughout the script. We need to mention this
piece of code in the ITestListener class in the “OnTestFailure” method.
Or
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
Example: In this example we will take screen capture of http://demo.guru99.com/V4/ & save it as
C:/Test.png
package Guru99TakeScreenshot;
import java.io.File;
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;
import org.testng.annotations.Test;
@Test
public void testGuru99TakeScreenShot() throws Exception{
WebDriver driver ;
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
driver = new FirefoxDriver();
//goto url
driver.get("http://demo.guru99.com/V4/");
/**
* @param fileWithPath
* @throws Exception
*/
Ashot is a third party utility by Yandex supported by Selenium WebDriver to capture the Screenshots.
Go to https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot
Step 1) Create an Ashot object and call takeScreenshot() method if you just want the screenshot for the
screen size page.
Step 2): Now, get the image from the screenshot and write it to the file. You can provide the file type as
jpg, png, etc.
Collection is a framework that contains interfaces and Classes which can be used to manipulate data in
the form of objects.
Hierarchy of Collection Framework
Core Interfaces in
Collections(collection,set,list,queue,dequeue,map)
The whole diagram is called as Collection Framework (framework is nothing but an architecture which
consists of interface and classes)
Collection(Root interface) Map
/ / \ \ |
/ / \ \ |
SortedSet
like PriorityQueue.
Deque : Elements can be inserted and removed at both ends. Allows
Comparator : It is an interface, using which we can definite a class which consists of the ways in which
we want to sort the elements in a list or set. These are custom defined class which consists of the way in
which the sorting has to be done. In other words these are used for custom ordering or custom sorting
of elements.
Enumerator : these are just used to iterate over collections. has 2 methods hasMoreElements(),
nextElement().Enumerator does not have remove().Enumeration interface acts as a read only interface,
one can not do any modifications to Collection while traversing the elements of the Collection.
Enumeration is a legacy interface which is used for traversing Vector, Hashtable.
Iterator : these are used to iterate over elements in a collections. has 3 methods hasNext(), next(),
remove(). Using Iterator we can do modifications to the collections as well. Iterator is not a legacy
interface. Iterator can be used for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap,
TreeSet .
SetSpeed(milliseconds) – Waits for amount of time mentioned in the parameter for executing
each line of command
Sleep(milliseconds) – Thread.sleep functionality.
Submit() or click() – both performs same action
findelement() – finds the first matching element in the page
findelements() – finds all the elements matching the locator and stores them in list
Datadriven framework – 1. Storing the values in external files like excel and then reading them
and storing them as variables and using these variables in our test methods. Data’s are not
stored in test methods. Only the test case steps or logic resides inside the test method.
Also Passing multiple test data’s for a same method. storing the test data’s in a
separate file. Either xml (testng xml) or excel
Selenium grid - Selenium Grid sent the tests to the hub. These tests are redirected to Selenium
Webdriver, which launch the browser and run the test. With entire test suite, it allows for
running tests in parallel.
How to get element background colour or element text colour of an element in selenium ?
Search for “iframe-tags”. In page source to find if there are iframes inside a page
switchTo.frame(frameindexnumber)
switchTo.frame(frame name or id)
switchTo.frame(webelement)
Finding total number of iframes. Creating a list which stores all the webelements with tag name
“iframeResult”.
Alerts are nothing but small popups/alert boxes appearing on the same tab or window.
driver.switchTo().alert().dismiss() ---- This method is used to click on the 'Cancel' button of the
alert.
driver.switchTo().alert().accept(); ----- This method is used to click on the 'Ok' button of the
alert.
getwindowhandles(): It is used to get the address of all the open browser and its return type is
Set<String>
getwindowhandle(): It is used to get the address of the current browser where the control is
and return type is string
By.id()
By.name()
By.tagName()
By.className()
By.linkText()
By.partialLinkText()
By.xpath
By.cssSelector()
How will you handle working with multiple windows in Selenium ?
selectWindow() – This is used to switch between windows. This command uses the title of
Windows to identify which window to switch to.
Mention why do you need Session Handling while working with Selenium?
So that multiple browsers would be opened at a same time and each different automated operations
would be performed on each of these browsers without interfering between one another. Also it is
possible to run a new script which will invoke browser even before the old script is over .Basically
multiple browsers run on a same machine and they should not disturb or interfere with one another. So
to avoid such situation you need Session Handling.
Synatax : Xpath=//tagname[@attribute='value']
Absolete xpath – long and big and starts from the starting node of the xml.
Relative Xpath – starts from the middle or anywhere in the page.
/ - single slash means that it is starting the xpath from the root node or the very first node of the page
that is available.
// - double slash means searching anywhere in the page and starting from the specified element.
XPath axes – Are methods to find complex or dynamic elements. Few commonly used axes methods in
selenium webdriver are child, parent, ancestor, sibling, preceding, self, etc.
How to insert or add or concatenate a string in the xpath that we are creating ?
String.format method is used to give formatted string. The first argument takes in the string containing
the format specifier. The second argument replaces the value in place of the format specifier.
Output :
name is sonoo
Method 1 :
driver.findElement(By.xpath(interpolation(element, "one"));
Method 2 (Easy):
Syntax : String.format(xpath containing %s, variable that we want to replace for %s)
driver.findElement(By.xpath(String.format("//*[@id='button-%s']", variable_replacementValue)));
1. Contains() - contain function inside Xpath has an ability to find the element with partial
text.
Xpath=//*[contains(@id,'sub')]
Xpath=//*[contains(text(),'here')]
3. Starts-with function – Finds the elements stating with the given value
Xpath=//label[starts-with(@id,'message')]
4. Text() – Used inside xpath to find elements with exact Text match.
Xpath=//td[text()='UserID']
20.1
driver.quit () – Used to close all the browser session along with the browser window, popup, tabs
associated with it.
20.2
boolean isVisible(webelement) – Checks whether this webelement is visible to the user on the UI. Some
elements might be hidden, Visiblity condition makes sure that the element is not hidden on the UI.
These calls are sent inorder to not load the whole page whenever we get any response from the server
for the desired browser action. Eg : We submit a form, now this request will be sent from browser to
server. Server’s response would be sent back to the browser. Now if the browser doesn’t load the whole
page inorder to show us the response for the Submit button. Then it is called as AJAX Calls.
Any actions that happens on the page without actually reloading the page, in these cases AJAX calls
were made from the browser by the application.
Waits times are difficult for AJAX calls. Cause we don’t know the load time.
Implicit wait – Waits for the element to be present on the page until the specified time or else throws
exception if the time limit is reached. If the element is found to be present much before the maximum
time specified, then it will move to next step.
Disadvantage : If we declare this implicit wait, then for our full script this will happen. i.e for each line.
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Explicit Wait :
Advantage over Implicit wait : This action can be performed to our desired piece of code. i.e Only for
the elements that we want.
Webdriver wait : Waits for the element until a specific condition is met. Or else waits for max time given
by the user before throwing exception. Polling is done after every 0.5 secs.
Polling is nothing but sending out the request to DOM (page source) to check whether the element
meets the mentioned condition.
The following are the Expected Conditions that can be used in Explicit Wait
1. alertIsPresent()
2. elementSelectionStateToBe()
3. elementToBeClickable()
4. elementToBeSelected()
5. frameToBeAvaliableAndSwitchToIt()
6. invisibilityOfTheElementLocated()
7. invisibilityOfElementWithText()
8. presenceOfAllElementsLocatedBy()
9. presenceOfElementLocated()
10. textToBePresentInElement()
11. textToBePresentInElementLocated()
12. textToBePresentInElementValue()
13. titleIs()
14. titleContains()
15. visibilityOf()
16. visibilityOfAllElements()
17. visibilityOfAllElementsLocatedBy()
18. visibilityOfElementLocated()
FleuntWait – It is same as WebdriverWait, but the only difference is here we can mentioned even the
polling frequency. I.e the frequency at which the condition check is done.
20.5 What is the difference between a truncate, drop and delete (SQL Question)
Delete – Delete few rows or full rows using WHERE clause. These changes can be rolled back.
(recovered)
Truncate - removes all rows from a table. This operation cannot be rolled back
Drop - removes a table from the database. All the tables' rows, indexes and privileges will also be removed.
This operation cannot be rolled back.
DROP TABLE emp
ROLLBACK - undo changes made to the database. Any command which was executed, will be undone.
Partial RollBack –
One can specify savepoints to mark a point in a transaction to rollback to. In the below example the Update
command which we performed is rolled back
Savepoint – It is a marker or point in an transaction to which you can later roll back.
Xpath CSS
full form - XML path Cascade Style Sheet
Both forward and backward traversal is supported Only forward traversal is supported
when compared to CSS, it is slower to find elements faster to find the element
Complex to read Easy to read
Constructor – It is a piece of code that is executed first as soon as the object of that class is created. The
constructor name has the same name to that of the Class name, but there are no datatype for
constructors.
Constructor Chaining – Calling one Constructor within another constructors with respect to current
object.
Withing Same class – it can be done using keyword this() . In the code, wherever this() is used.
TIPS FOR UNDERSTANDING EASILY : Consider it is similar to constructorName(). i.e instead of using the
“Constructor” name once again, we are using this(). But functionality wise both are same. When this() is
used, imagine replacing it with current class name. When super() is used, consider replacing it with Base
class name.
From base class - by using super() keyword to call constructor from the base class.
Order of execution : While traversing in the constructor chaining, the piece of code within the last
traversed constructor would be executed first followed by the next topmost constructor. Like wise.
Rules for Constructor chaining : 1. Atleast one constructor should be without this() keyword. 2. First line
of the constructor should contain this().
Instead of writing all the piece of code within a same constructor, we are storing each code in different
constructors. One of the example is using super(driver) is in automation for each page object class. We
call super(Driver) so that the driver that is returned from the base class is called.
20.9 Init block – these are nothing but the piece of code which is written within open “{“ and closed
parenthesis “}” within a class. On creating an object all the code within this init block is executed first,
then only even the constructor is called. Similar to Constructor but this is executed first before even
calling the constructor.
class Temp
{
// block to be executed before any constructor.
{
System.out.println("init block");
}
20.10 Multiple inheritance not supported in Java because it causes confusion if a method with same
name is present in more than 1 classes.
Whereas using interface, Java supports multiple inheritance. In this we use the keyword Super() to
specify which method to be called.
Syntax : InterfaceName.Super.MethodName();
java.lang.Object
Compareto() – Compares the Unicode value of the two strings and gives the difference in integer
format. 0 means both are same strings.
Compare – compares the ASCII value of the two strings and gives the difference in integer format. 0
means both are same strings.
equals() – compares whether the content of 2 objects are equal or not even if both the objects are
different. Returns true or false.
== (equalTo) – does the same job of equals(), but only if both the objects are same and of same
datatype as well.
Steps :
1. Get the window id of current window (parent window) using getWindowHandle and
store it in a variable
2. Get all the window id using getWindowHandles and store them in a set or list.
3. Now remove our parent windowhandle from the above set. Now we will be left with only
the child window id’s
4. Iterate over to the desired child id and then switch back to parent window handle
whenever required.
20.14 Typecasting – The process of converting value of one datatype to another datatype.
2nd way (best way): Narrowing Type Casting – We manually change from one datatype to another by
putting the datatype which we needed within parenthesis.
Math.Log function returns doubt data type. Now we have converted that double to int using
typecasting.
setProperty is use for setting the path of the driver of the respective browser that we want to run the
scripts.
Since the browsers doesn’t have an inbuilt server to run the automation code, we have to mention the
driver and its path manually before starting any automation script.
Example :
System.setProperty("webdriver.chrome.driver","C:\\Utility\\BrowserDrivers\\
chromedriver.exe");
Actions class is a built-in ability to handle various types of keyboard and mouse events.
Used for accessing the drop-down box, double click, right click, click enter button, drag and drop,
keyboard short cut actions etc
Note : Right click is also called as “context click” in selenium
Example 1 :
Actions action = new Actions(driver);
action.moveToElement(element).perform();
action.doubleclick().perform();
Example 2 :
Actions action = new Actions(driver);
action.moveToElement(element).doubleclick().build().perform();
Example 3 :
Actions builder = new Actions(driver);
builder.clickAndHold(element1).clickAndHold(element2).click().build().perform
();
Note : Usually for a single action we can just use either build() or perform(). Not necessary to use both.
Even using both is not an issue.
But when we are doing a multiple operations to be performed like, then we need to use build() and
perform() for compiling and executing.
build().perform() ---> this method is used to compile(build) and execute(perform) the action class
Please note that the normal webelemt class supports simple methods like click(), submit(), sendkeys().
Those doesn’t come under action class, hence you need not use build, perform or action class object for
those.
import org.openqa.selenium.Keys
WebElement.sendKeys(Keys.RETURN);
Or
driver.findElement(By.id("Value")).sendKeys(Keys.ENTER);
20.17 Can we run our automation script even without installing chrome browser in our system ?
Yes we can run automation scripts even without installing chrome browser in UI. We can run the
automation script using headless browser. This is useful when we have to run an automation script in a
server, where browser install options are not there.
1. Saves time and is faster since we really can’t see this browser on the screen and it only runs on
the background.
2. You could use the installed browser for some other testing purpose.
Syntax :
System.setProperty("webdriver.chrome.driver","ChromeDriverPath");
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
options.addArguments("window-size=1200x600");
1. SendKeys() – Used to enter text into the Text Fields and Password Fields
Syntax : Webelement.sendkeys(“xyz”);
4. Submit() – Used to submit the entire form to the server. It is supported only if the webelement
is a button. Usually for a button, both submit() and click() behaves the same.
Syntax : webelement.submit();
20.20 How to check if an element is present, enabled, visible, find text in selenium webdriver
if(driver.findElements(By.xpath("value")).size() != 0){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
Or
if(driver.findElement(By.xpath("value"))!= null){
System.out.println("Element is Present");
}else{
System.out.println("Element is Absent");
}
2. To check Visible:
3. To check Enable:
Using “Select” class we can pass the values that we want for our dropdown. The dropdown tag should
be “Select” inorder to do this.
20.22 How to get the text from a page and store it in a file.
getText() – This method is used to get the text value of the webelement
File – File class is used for creating file objects. Cause only file objects are supported in FileUtils class
methods.
FileUtils.writeStringTofile – is used to store the string to the destination file.
String output = driver.findElement(By.id("abc")).getText();
File DestFile= new File("extractedFilePath"); //file is a class used for
creating file objects
FileUtils.writeStringToFile(DestFile, output);
contentEquals(File file1, File file2): It compares the contents of 2 File objects, and returns whether they
are the same or not.
write(File file, CharSequence data): Writes a CharSequence in a file, using the specified enoding.
writeStringToFile(File file, String output): Writes the string into the specified file.
copyFile(File sourcefile, File destinationfile) : copies the content of one file to another file, it overrides
the content in the destination file.
20.24 How to count the number of elements (say links, or anyother element) using selenium
Steps :
1. Find all the elements using findelements method and store them in a Webelement List.
2. Find the size of the webelement list, it will give us the total count of the elements.
Example 1 :
List<WebElement> xpath =
driver.findElements(By.xpath("//div[@id='billingProfiles']/div[@class='cardCon
tainer']"));
20.25 Clicking back button/ forward button/ refreshing a webpage using Selenium
driver.get() : It's used to go to the particular website , But it doesn't maintain the browser History and
cookies so , we can't use forward and backward button , if we click on that , page will not get schedule
driver.navigate().to() : it's used to go to the particular website , but it maintains the browser history and
cookies, so we can use forward and backward button to navigate between the pages during the coding
of Testcase
String titleofthepage = driver.getTitle(); //gettitle method is used to get the title of the webpage
And using asserting we can assert whether the value of the title is correct as we expected or not
assertArrayEquals(expectedArray, resultArray);
assertEquals(String Actual, String expected);
assertNotEquals(String Actual, String expected)
assertTrue(Boolean abc) – the assertion is successful if the condition returns TRUE
assertFalse(Boolean abc) – the assertion is successful if the condition returns FALSE
assertNull(variable or object): the assertion is successful if the expected output is null.
assertNotNull(variable or object) : the assertion is successful if the expected output is not null.
Softassert syntax :
Immutable class means that once an object is created, we cannot change its content. In Java, all
the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable by default.
Any variable created with the above classes, its content cannot be modified. Once initialized its value
cannot be modified.
Cookies :
System.setproperty
We need not write system.setproperty at the start of out automation script each time, provided we
added this location in the “Environment variable” settings in the “System” app in the windows.
Open “systems” -> Advanced system settings -> environment variables ->Edit path and add this path as
well where the driver should be present.
System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
https://www.guru99.com/desired-capabilities-selenium.html
The desired capability is a series of key/value pairs that stores the browser properties like browsername,
browser version, the path of the browser driver in the system, etc. to determine the behaviour of the
browser at run time.
Selenium consists of : selenium ide , selenium webdriver (webdriver + selenium rc), selenium grid.
Selenium ide : uses the language called selenese. Build in feature of Firefox, where we record and run a
scenario. Not suitable for large code base, and changing data’s
Selenium rc : We can write the code in any complex language (java, python etc). But it doesn’t directly
interact with browser. It sends the code to Selenium RC server. Server then sends to Browser in the form
of Javascript. As selenium rc is not directly communicating with browser, it is not so fast. Also due to
javascript injection there can be some issues. Eg : sometimes if a field is not editable, but with javascript
that would still pass values without errors.
Webdriver : Directly communicates with the browser application in the Operation system. Supports
working in various operating systems and browsers. It is faster.
Selenium grid : It is a component of selenium rc which is used to run multiple test cases parallely in
various browsers as well.
Selenium Code :
File file = new File("D:/Dev/ReadData/src/datafile.properties")
FileInputStream fileInput = new FileInputStream(file);
Properties prop = new Properties();
prop.load(fileInput);
driver.get(prop.getProperty("URL"));
System.out.println("URL ::" + prop.getProperty("URL"));
System.out.println("User name::" +prop.getProperty("username"));
System.out.println("Password::" +prop.getProperty("password"));
Output :
URL ::http://gmail.com
User name::testuser
Password::password123
We can use setProperty() method to update an existed key-value pair or add a new key-value pair.
props.setProperty("name", "NewAppName"); // Create a new value or update an old value
If you want to remove a key-value pair, you can use remove() method.
Props.remove("keyname");