0% found this document useful (0 votes)
9 views115 pages

Automation Testing

The document provides a comprehensive overview of automation testing, focusing on tools like Selenium and Java, and covers various topics including setup, basic commands, and handling web elements. It distinguishes between manual and automation testing, explaining the benefits of automation, and details the components and locators used in Selenium. Additionally, it includes practical examples and methods for handling alerts, dropdowns, and window management in testing environments.

Uploaded by

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

Automation Testing

The document provides a comprehensive overview of automation testing, focusing on tools like Selenium and Java, and covers various topics including setup, basic commands, and handling web elements. It distinguishes between manual and automation testing, explaining the benefits of automation, and details the components and locators used in Selenium. Additionally, it includes practical examples and methods for handling alerts, dropdowns, and window management in testing environments.

Uploaded by

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

Automation Testing

By Kannathasan E
Topics to be covered
● What is Manual and automation testing?
● Setup
● Why Java and Selenium Required
● Selenium overview
● HTML Basic
● Selenium locator and types
● Selenium webdriver hierarchy
● Basic Selenium commands
● Alert Handling
● Drop down handling
● File Uploading
● Window handling
● Screenshots
● Waits in selenium
● iFrame handling
Topics to be covered
● Keyboard and Mouse hover handling
● JavascriptExecutor
● WebDriver Manager
● Web Table
● TestNG framework - (Data Provider)
● How to read the data from excel file - Apache POI
● Basic of Maven
● Basic of POM
● What is framework and it is types?
● Data Driven framework and explanation with demo.
● Basic of Git and it commands
Overview of Testing
Manual Testing vs Automation Testing
Manual Testing
● Performing the testing without using any tools is known as Manual
Testing. Here a tester / person will do the testing.
Automation Testing
● Performing the testing with the help of tools is known as Automation
Testing. Here instead of a person, a tool will perform the testing. The
tool used for replacing the person is nothing but a Test Automation
tool (Selenium , Test Complete etc.,)
● Automation testing helps in reducing the test execution time.
How can a tool perform Testing ?
● Testers will do some coding and put the developed code into the
Automation tool. Automation tool will perform testing with the help of
the code developed by the testers.
When to Automate?
Setup
● Download Java 11 version-
https://www.oracle.com/in/java/technologies/javase/jdk11-archive
-downloads.html
● Java -version
● JAVA_HOME - JDK path - In user variable environment
● Path - Add JDK till Bin
● Eclipse -
https://www.eclipse.org/downloads/packages/release/2019-12/r
● Go to the software which is download and click the exe file
● ChromeDriver - https://chromedriver.chromium.org/downloads
● https://googlechromelabs.github.io/chrome-for-testing/
Why JAVA?
● Open source
● Widely used
● Matured language existing over 20 years
● Used in multiple companies
● Lot of libraries available
● Based on OOPS
● Selenium with Java have most of the Jobs in the market
Why JAVA?
● Open source
● Widely used
● Matured language existing over 20 years
● Used in multiple companies
● Lot of libraries available
● Based on OOPS
● Selenium with Java have most of the Jobs in the market
Software required
● Java - Installing Java 8 - Setting environment Variables
● Human readable code to machine readable code (0’s and 1’s) ( By Compiler) it
is under Jdk(Java development kit) -> bin->javac
● Java Runtime environment ( You can only run) -> Jre file you can see only Java
file
What is IDE?
● Integrated Development Environment
● Eclipse or Intellij
● Intellij Download
Selenium
Selenium in simple terms is a Test Automation Tool. i.e. Instead of a person
performing testing manually, Selenium tool will automatically perform the testing
with the help of developed code.
Type of Applications that Selenium can automate
● Selenium can only automate Web Applications (i.e. The applications which run
on the browser).
Example: https://www.msn.com
● Selenium cannot automate Desktop Applications or Mobile Applications (i.e.
The applications which don't run on the browsers).
Example: Skype, Adobe PDF Reader and many more.
● Selenium is a free tool (Opensource) (i.e. You don’t need to pay any license
amount for using Selenium tool.)
Different Browsers supported by Selenium
Different Operating Systems / Programming Languages
supported by Selenium
Different Components in Selenium
Selenium is not a single tool. Instead it is a combination of tools like
Selenium IDE, Selenium RC, Selenium WebDriver and Selenium Grid. Out
of all these tools, Selenium RC is outdated and can be ignored completely.
Different versions of Selenium
Java Concept you should Aware
● Array
● String
● Interface
● Class
● Conditional statements
● Abstract Class
● Abstract Method
● Inheritance
● List / Set
● Return Type
● Exception handling
● File Handling
HTML Tags
<html> HTML Document
<head> Page Information
<title> Name in the title bar
<body> Page Contents
Lists
<ul> Unordered List
<ol> ordered List
<li> List item
<dl> Definition List
<dt> Definition Term
<dd> Term Description
Continue..,
Links

<a href="url"> Page Link

<a href="mailto"> Email Link

<a href="to top"> Anchor

<a href="#Contact Us"> Link to Anchor

<a href="HomePage.html#name"> Link to Anchor

Forms

<form> Forms

<select> Drop Down Box

<textarea> Large Input Text

<input type="checkbox"> Checkbox

<input type="text"> Text Input

<input type="radio"> Radio Button

<input type="submit"> Submit Button

<input type="reset"> Reset Button

<input type='file"> Browser file button


Selenium Webdriver 4 Hierarchy
What is Selenium Locator
● Selenium Locators are used for identifying the web elements on the
web page. To access the HTML elements from a web page locators
are used. In Selenium, we can use locators to perform actions on text
boxes, checkboxes, links, radio buttons, list boxes, and other web
elements. Locators help us in identifying the objects
Why we need to use different locators?
● Sometimes developers may not provide all locators for all elements
● Some locators may be duplicated sometimes.

So we have to choose any one unique locator to identify the element


Selenium Locators
Selenium locators are used to identifying the web elements on the
web page
Find Element / Elements difference
ID Locator
● Ids’ are the most preferred way to locate elements on a web page, as each id is
supposed to be unique which makes ids faster and more reliable way to locate
elements on a page.
● A NoSuchElementException will be raised, if no element has a matching id
attribute.
driver.findElement(By.id("email"));

sendKeys("[email protected]");

//id locator for text box

● Even though id is the most preferred locator, obviously it is not realistic for all
objects to have ids on a web page. In some cases, developers will give non-unique
ids on a web page, in that case id should be avoided.
● NoSuchElementException Happens when the locators are unable to find or
access elements on the web page or application. Ideally, the exception occurs due
to the use of incorrect element locators in the findElement(By, by) method.
● To handle this exception, use the wait command. Use Try/Catch to ensure that the
program flow is interrupted if the wait command doesn’t help.
Name Locator
● This is also the most efficient way to locate an element with a name
attribute. With this strategy, the first element with the value name
attribute will be returned.

● A NoSuchElementException will be raised, if no element has a


matching name attribute.

● In case it is having the same name it will perform the action of the first
finding the element

● driver.findElement(By.name("login")).sendKeys("seleniumtesting@yah
oo.com"); //name locator for text box
LinkText Locator
● Selenium linkText locator is used for identifying the hyperlinks on a
web page. It can be identified with the help of an anchor tag “a”. In
order to create the hyperlinks on a web page, you can use anchor
tags.

● driver.findElement(By.linkText("Difficulty signing in?")).click();


//linkText locator for links
Partial Link Text Locator
● In some situations, we may need to find links by a portion of the text
in a link Text element. In those situations, we use Partial Link Text to
locate elements.

● when we have various hyperlinks with the exact text on the web page,
Selenium would go on to choose the one that appears first.

● driver.findElement(By.partiallinkText("Difficulty")).click();
//partiallinkText locator for links
Tag Name Locator
● The TagName locator in Selenium can use HTML tag names such as
div, button, input, anchor tag, and so on to identify web page
elements.

● By.tagName("a");

("a"): The tagName locator returns all the elements from the page that
contains a specified tag “a”

https://dzone.com/articles/locating-elements-by-tagname-in-selenium
Class Name Locator
● Use the Class attribute for identifying the object
● https://dzone.com/articles/selenium-java-tutorial-class-name-locator-i
n-selen
CSS Syntax
CSS Selector Locator
● https://www.toolsqa.com/selenium-webdriver/css-selectors-in-seleniu
m/
● CSS selector is always faster than Xpath
XPATH
● XPath stands for XML (Extensible Markup Language) Path language
There are two types of XPath in Selenium.
Absolute XPath
Relative XPath
Absolute Xpath
● It is the easiest way to find the element but if any changes are made
in the path of the element then this XPath gets failed. So, This is the
main disadvantage of absolute XPath.
● It begins with a single forward slash (/) which selects the element
from the root HTML node
● E.g - /html/body/div/div[1]/div[2]/form/div[3]/div/div/div[2]/input

Syntax - Xpath = /tagName[@attribute=attribute's value]


Relative Xpath
● It starts from the double forward slash(//) and selects the element
from anywhere on the webpage.
● It is the best practice to find an element through a relative XPath and
helps us to reduce the chance of “element not found exception”.
● With a relative XPath, we can locate an element directly irrespective of
its location in the DOM.
● E.g - //*[@id="username"]

Syntax - Xpath = //tagName[@attribute=attribute's value]


Syntax of XPath
Xpath = //tagName[@attribute=’attribute's value’]
● tagName - tag name is nothing but the name which is present after
the < (angular bracket)
● @: is the Select attribute
● attribute - whatever is present inside < and > bracket except
tagname is an attribute, any number of attributes can present in
HTML code
● attribute's value - it is corresponding value to the attribute,
sometimes for boolean attribute developers may not specify any
value; in those cases, HTML takes 'true' as default value.
● https://www.lambdatest.com/blog/complete-guide-for-using-xpath-in-
selenium-with-examples/
Key Points to Remember About locator
● The priority of locator type in this order: id > name > CSS> XPath.
● It is important to use an appropriate locator to identify an
element on the page that must be unique.
● If an element is associated with a link, use linkText or
partialLinkText to identify element.
● https://www.lambdatest.com/blog/selenium-locators-cheat-sheet/
Basic Selenium commands
● get() - driver.get("http://tutorialsninja.com/demo/"); (Don’t add url
without http or https) - you will be getting the
InvalidArgumentException
● maximize() - driver.manage().window().maximize();
● fullscreen() - driver.manage().window().fullscreen();
● findElement() Command - WebElement textArea =
driver.findElement(By.id( "ta1")); - NoSuchElementException
● click() Command
● sendKeys() Command
● clear() Command
● getText() Command
● getTitle() Command
● getCurrentUrl() and getPageSource()Command
● close() and quit()Command
● getAttribute() Command
Navigation Commands
1. To Command - to(String arg) : void
● The to() method takes a String parameter and returns nothing.
● This method is used to navigate the URL of the web page in the
current browser window. It will just navigate to the web page but
not wait till the whole page gets loaded.
2. Forward Command - The forward() method neither accepts nor
returns anything.
● This method is used to move forward by one page on the
browser’s history.
3. Back Command -The back() method neither accepts nor returns
anything.
● This method is used to move back by one page on the browser’s
history.
Navigation Commands
4. Refresh Command -The refresh() method neither accepts nor returns
anything.
● This method is used to refresh the current web page.
● It performs the same function as pressing F5 in the browser.
Examples
● Navigate To Command - driver.navigate().to("www.flipkart.com");
● Forward Command - driver.navigate().forward();
● Back Command - driver.navigate().back();
● Refresh Command - driver.navigate().refresh();
● All the above method return type is VOID
Alert Handling
● Alert is class - driver.switchTo().alert() / You can’t Inspect Alert
There are 3 types of alert - https://letcode.in/alert
● 1. Simple
● 2. Confirm
● 3. Prompt
Methods can be performed in the alert are
● 1. Accept - alert.accept();
● 2. Dismiss - alert.dismiss();
● 3. getText - alert.getText();
● 4. sendKeys - alert.sendKeys("Kanna"); - You can’t view the typing part in alert
Exceptions:
● 1. UnhandledAlertException
● 2. NoAlertPresentException
alertIsPresent() Command - wait.until(ExpectedConditions.alertIsPresent());
Windows Authentication popup - https://the-internet.herokuapp.com/
Drop Down Handling
● The Select Class in Selenium is a method used to implement the
HTML SELECT tag. The html select tag provides helper methods to
select and deselect the elements. The Select class is an ordinary class
so New keyword is used to create its object and it specifies the web
element location. https://letcode.in/dropdowns
● Select select = new Select(WebElement webelement);
Drop down Method syntax - Select
● Select select = new
Select(driver.findElement(By.id("oldSelectMenu")));
● selectByIndex(int arg0) : void
● selectByValue(String arg0) : void
● selectByVisibleText(String arg0): void
● All the above method return type is VOID
Examples:
● se.selectByIndex(3);
● se.selectByValue("6");
● se.selectByVisibleText("White");

● isMultiple(): boolean
● isMultiple() " method, which determines whether the web element in say
supports multiple selections. It returns a boolean value, i.e., True/False,
without taking any argument.
Drop down Method syntax - deselect

Select se = new Select(WebElement webelement);


● deselectAll(): void
● deselectByIndex(int arg0): void
● deselectByValue(String arg0): void
● deselectByVisibleText(String arg0): void
Examples:
● select.deselectAll();
● select.deselectByIndex(1);
● select.deselectByValue("6");
● select.deselectByVisibleText("White");
Drop down Method syntax - getOptions
● getOptions(): List<WebElement>
● getFirstSelectedOption(): WebElement
● getAllSelectedOptions():List<WebElement>
Examples:
● List<WebElement> options = select.getOptions();
● WebElement firstSelectedOption = select.getFirstSelectedOption();
● List<WebElement> selectedOptions = select.getAllSelectedOptions();
Exception
UnsupportedOperationException - You can Only deselect options of multi
select
Window Handling
● A window handle stores the unique address of the browser windows. It is
just a pointer to a window, whose return type is alphanumeric. The window
handle in Selenium helps in handling multiple windows and child windows.
Each browser will have a unique window handle value with which we can
uniquely identify it.
● getWindowHandle( ): When a website opens, we need to handle the main
window i.e the parent window using driver.getWindowHandle( ); method. With
this method, we get a unique ID of the current window which will identify it
within this driver instance. This method will return the value of the String
type.
● getWindowHandles( ): To handle all opened windows which are the child
windows by webdriver, we use driver.getWindowHandles( ); method. The
windows store in a Set of String type and here we can see the transition from
one window to another window in a web application. Its return type is Set
<String>.
● switchto(): Using this method we perform switch operation within windows.
● NosuchWindowExecption
Selenium Commands - cont..
● Many a time a test fails when we click on an element or enter text in a field.
This is because the element is displayed or exists in DOM, but it does not exist
on the web page.
● The result would be that there was an error and the test failed. So, we can
handle these kinds of problems by checking the visibility of web elements on
webpage. We can easily know the state of an element.

1. isDisplayed() - boolean eleSelected=


driver.findElement(By.xpath("xpath")).isDisplayed();
2. isSelected() - boolean elePresent =
driver.findElement(By.xpath("xpath")).isSelected();
3. isEnabled() - boolean eleEnabled=
driver.findElement(By.xpath("xpath")).isEnabled();
Why we need Screenshot?
Failures may occur because of below reasons:
● Actual and Expected values are not matching
● When there is no element
● When the page takes more time to load
● When there are Assertion issues
Multiple Inheritance concept
● Our browser classes (Like ChromeDriver, FirefoxDriver) extends RemoteWebdriver,
and RemoteWedriver implements TakesScreenshot Interface along with Webdriver
Interface.
● So we have screenshot method implementations in our driver classes. This process
is called Multiple Inheritance in java, i.e., Class(browser) implementing two
Interfaces(Webdriver and TakesScreenshot)
Screenshot Method
● Selenium provides TakesScreenshot interface to capture the screenshots
during script execution. TakesScreenshot interface has method
getScreenshotAs( ) which is used for taking screenshots.
● Taking screenshots when the test case fails is very common requirement in
any test automation and your test automation framework should have
capability to take screenshots in case you need them for reporting and
debugging purposes.
● Add the following dependency -
https://mvnrepository.com/artifact/commons-io/commons-io
● Code snippet
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, newFile("./Screenshots/Selenium" +
System.currentTimeMillis() + ".png"));
iFrame
● iFrame in Selenium Webdriver is a web page or an inline frame which is
embedded in another web page or an HTML document embedded inside
another HTML document.
● The iframe is defined with the <iframe> tag.
● We can even identify total number of iframes by using below snippet.
● Int size = driver.findElements(By.tagName("iframe")).size();
How to switch over the elements in iframes using WebDriver commands:
Basically, we can switch over the elements and handle frames in Selenium using 3
ways.
By Index
By Name or Id
By Web Element
iFrame
iFrame - Continue..,
Switch to the frame by index:
● Index of the iframe starts with ‘0’.
● Suppose if there are 100 frames in page, we can switch to frame in Selenium
by using index.
● driver.switchTo().frame(0); / driver.switchTo().frame(1);
Switch to the frame by Name or ID:
● Name and ID are attributes for handling frames in Selenium through which we
can switch to the iframe
● driver.switchTo().frame(“iframe1”); / driver.switchTo().frame(“id of the
element”);
Switch to the frame by Web Element:
● driver.switchTo().frame(WebElement);
How to switch back to the Main Frame
● driver.switchTo().parentFrame(); / driver.switchTo().defaultContent();
iFrame
What is Wait? Why we need it ?
● It is the process of matching the speed of action and reaction, selenium does
the action, and web application shows the reaction.
● In most of the cases, the selenium does the action in micro or milliseconds,
but the application takes time in seconds.
● At the same time, selenium will not wait till it loads or becomes visible at the
time selenium will not able to find the element within the java processing time
so selenium throws “NoSuchElementException᾿.
● We cannot alter the speed of the application, so we must slow down selenium.
● Sleep() method will not worry about whether the element is present or not; it
just sleeps till the mentioned time. This is also called a static wait or blind wait,
dead wait.
ElementNotVisibleException - When webdriver is able to locate web element on
current webpage but it is not visible on screen.
NoSuchElementException
Thread.sleep() reduces the performance of the code to a greater extent and it's
not recommended.
Waits in Selenium
● Implicit Wait
● Explicit Wait
● Fluent Wait — not much used so we are not gonna cover this and please read
by ur self
Implicit Wait - Implicit wait specifies the amount of time the driver should wait
when searching for an element if it is not immediately present.
driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
E.g driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Implicit wait will accept 2 parameters, the first parameter will accept the time as an
integer value and the second parameter will accept the time measurement in
terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS,
DAYS, HOURS, etc.

When the application is slow and network issue Implicit wait is better choice
Implicit Wait Selenium
● Selenium tries to find the element without bothering about whether elements
are loaded or not, and selenium throws NoSuchElementException if the
element is not present.
● Implicitly wait is one of the ways to request selenium not throw any exception
until provided time.
● The default wait time of the selenium is 500 milliseconds, implicitly wait
overrides the default wait time of the selenium.
● If the element is found before implicitly wait time, selenium moves to the next
commands in the program without waiting to complete the implicitly wait
time; this wait is also called dynamic wait
● Once you set implicit wait, it will be applicable to all calls of findElement() and
findElements() methods.
Implicit Wait Selenium
● You must be thinking, sleep() and implicit wait sound same in behavior then
what is difference? Why should we use implicit wait over sleep()?
● Because Implicit wait is a dynamic wait. When we use sleep() method, it
makes the current thread idle unconditionally. It means if we set sleep
timeout as 5 seconds, thread will wait for 5 seconds completely (If not
interrupted). But if we use implicit wait, it waits for an element to be present
but does not sit idle. It keeps polling for element and returns as soon as
element is found.
● So if we set implicit wait as 10 seconds and element is found in 5
seconds, driver will NOT wait for remaining 5 seconds. It saves 5 seconds
of execution time. In short , sleep will sit idle for specified timeout and after
timeout we need to look for element explicitly but implicit wait does both
steps together and that too dynamically.
Pros and cons of Implicit Wait
● We cannot mention any explicit condition to be met before performing any
operation using Implicit Wait.
● Implicit Wait, will not bother if the element is hidden or can be interacted. If
the element is present in the DOM, it will immediately release the wait and will
start performing the further operations which are not desirable at most of the
situations.
● Implicit Wait is applicable for all the web elements found using the web driver
and implicit wait has power until driver.quit() is encountered.
● We can't control the polling time-frequency using implicit wait.
Explicit Wait Selenium
● Explicit wait can be called as conditional wait / WebdriverWait.
● The explicit wait is used to tell the Web Driver to wait for certain conditions or
the maximum time limit before throwing an Exception .
● WebDriver throws "ElementNotVisibleException" if explicit wait fails.
● WebDriverWait is the class
● ExpectedConditions is the class / ExpectedCondition is Interface

Syntax Explicit Wait


WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());
Explicit Wait - Expected Conditions
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()
Pros and cons of Explicit Wait
● We can mention any (inbuilt conditions are plenty and that is more than
enough for any web applications) explicit condition to be met before
performing any operation.
● Explicit wait performs very well when compared to implicit wait and is the
widely used wait condition.
● Explicit Wait is applicable for only the web elements found using the webdriver
wait and has no control over other elements found normally.
● We can't control the polling time-frequency using Explicit wait. Same is the
case with the implicit wait.
—-----------------------------------------------------------------------------------------------------------
Page load timeout in selenium requests/set the time limit for a page to load, If the
page is not loaded within the given time frame selenium throws
TimeOutException.
driver.manage().timeouts ().pageLoadTimeout (30, TimeUnit.SECONDS);
Keyboard and Mouse Hover Actions
● Actions Class in Selenium is a built-in feature provided by the selenium for handling
keyboard and mouse events. It includes various operations such as multiple events
clicking by control key, drag and drop events and many more

Actions action = new Actions(driver);


Create object of an Actions Class
by passing the WebDriver instance
Keyboard Events
● sendKeys(keysToSend) : sends a series of keystrokes onto the element
● keyDown(theKey) : Sends a key press without release it. Subsequent actions may
assume it as pressed. (example: Keys.ALT, Keys.SHIFT, or Keys.CONTROL)
● keyUp(theKey): Performs a key release
Mouse Events
● click (): Simply click on element
● doubleClick (): Double clicks on Element
● contextClick() : Performs a context-click (right click) on an element
● clickAndHold(): Clicks at the present mouse location (without releasing)
● dragAndDrop(source, target): Invokes click-and-hold at the source location and moves
to the location of the target element before releasing the mouse. source – element to
grab, target – element to release
● dragAndDropBy(source, xOffset, yOffset) : Performs click-and-hold at the source
location, shifts by a given offset, then frees the mouse. xOffset – to shift horizontally,
yOffset – to shift vertically
● moveByOffset(x-offset, y-offset): Shifts the mouse from its current position (or 0,0) by
the given offset. x-offset – Sets the horizontal offset (negative value – shifting the mouse
to the left), y-offset – Sets the vertical offset (negative value – shifting the mouse to the
up)
● moveToElement(toElement): It shifts the mouse to the center of the element
● release(): Releases the depressed left mouse button at the existing mouse location
File Uploading
● We can upload files using Selenium Webdriver. This is achieved by the sendKeys method.
We have to first identify the element which performs the file selection by mentioning the
file path
● This is only applied to an element having a type attribute set to file as a value along with
the element tag name as input.
Javascript Executor
● JavascriptExecutor Interface
● JavascriptExecutor is an interface present under org.openqa.selenium package in Selenium
Webdriver. JavascriptExecutor Interface has two abstract methods which are :
● executeScript()
● executeAsyncScript()
● To use Javascript Executor, we may require little or no knowledge of javascript.
Syntax
// cast the driver object to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
// access the methods
js.executeScript("javascript command");
js.executeAsyncScript("javascript command");
When to use Javascript Executor
● When the normal click() is not working
● Selenium WebDriver don't have the capability to scroll the page
● And many more cases, where Selenium WebDriver's default things are not
going to help
Javascript Executor Commands
● To Scroll down
jse.executeScript("window.scrollBy(0,600);");
● To Scroll up
jse.executeScript("window.scrollBy(0,-300);");
● To click
jse.executeScript("arguments[0].click()",alertbutton);
● To send the value
jse.executeScript("arguments[0].value='[email protected]",email);
● To get the value of the WebElement
js.executeScript("return arguments[0].innerHTML;",element));
WebDriverManager
● We need to download driver executables manually and set path
for the same.
● As and when browser version is updated, we need to download
driver executable/s that can be matched with latest browser
version.
● We need to set exact path for driver executable/s else we get
illegalStateException. [When we try to launch browser without
setting correct path for driver executable/s]
● WebDriverManager is an API that allows users to automate the
handling of driver executables like chromedriver.exe,
geckodriver.exe etc required by Selenium WebDriver API.
● https://mvnrepository.com/artifact/io.github.bonigarcia/webdriver
manager/3.8.1
● WebDriverManager.chromedriver().setup();
TestNG
● TestNG is a testing framework inspired from JUnit and NUnit but introducing
some new functionality that makes it more powerful and easier to use.
● TestNG is one of the most widely used open source testing framework used in
automation testing suite
● It is an open-source automated testing framework; where NG of TestNG
means Next Generation
● TestNG is similar to JUnit but it is much more powerful than JUnit but still, it's
inspired by JUnit. It is designed to be better than JUnit
● https://testng.org/
● Installation Guide -
https://www.lambdatest.com/blog/how-to-install-testng-in-eclipse-step-by-ste
p-guide/
Advantage of TestNG
● It gives the ability to produce HTML Reports of execution
● Annotations made testers life easy
● Test cases can be Grouped & Prioritized more easily
● Parallel testing is possible
● Generates Logs
● Data Parameterization is possible
Annotations
● https://www.simplilearn.com/know-about-testng-annotations-in-selenium-web
driver-article
● Suite: A suite is made of one or more tests.
● Test: A test is made of one or more classes.
● Class: A class is made of one or more methods.
Annotations
TestNG Xml file Creation

TestNG Assertion
How to set the Priority
How to Skip the test case from execution
How to declare dependsOnMethod
How to run test cases parallel

https://learn-automation.com/parallel-execution-in-selenium/
Where to see the Reports? In TestNG
How to run failure test cases
@Test Attributes
How to run group of test cases
DataProvider in TestNG
Advantage of TestNG
● @Test: Methods annotated with @Test are called test methods that serve as a
unit test. In @Test methods, we will write the logic of the application which we
want to automate.
● We can pass attributes to our test method. The output depends on these test
methods for success or failure.
Read data from Excel
Dependency

1. Apache POI

2. Apache POI - OOXML

What is Apache POI?

Apache POI, where POI stands for (Poor Obfuscation Implementation) is an API that offers a collection of
Java libraries that helps us to read, write, and manipulate different Microsoft files such as excel sheets,
power-point, and word files.

https://mvnrepository.com/artifact/org.apache.poi/poi

https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml

Pre- condition

1. Create an excel file with data

Steps to implement

1. Locate the file 2. Locate the workbook & Sheet 3. Read the data from the cell (Rows & Column)

4. Close the resource


Read data from Excel
Maven
● Maven is one of the most important technologies to be mastered by every
Java professionals. Maven cannot be defined as a single purpose tool. It
performs a variety of operations like providing templates for Java projects,
organising the project structure, managing the dependencies, creating
documentation site etc
● A build is nothing but a process of converting the source code into a
deployable or installable or distributable file format
● Maven has three important life cycles called default, Clean and site. And
each cycle has several phases associated with them.
● Maven Installation: Follow the below link:
● https://www.mkyong.com/maven/how-to-install-maven-in-windows/
● https://www.lambdatest.com/blog/getting-started-with-maven-for-selenium-te
sting/
● https://www.gcreddy.com/2018/08/introduction-to-maven.html
● https://www.javatpoint.com/selenium-maven
● https://automationtestings.com/maven-tutorial-selenium/
Maven - How it works
POM
What is Page Object Model in Selenium?
Page Object Model, also known as POM, is a design pattern in Selenium that creates an object
repository for storing all web elements. It is useful in reducing code duplication and improves
test case maintenance.
In-Page Object Model, consider each web page of an application as a class file. Each class file
will contain only corresponding web page elements. Using these elements, testers can
perform operations on the website under test.
Framework
● A framework defines a set of rules or best practices that we can follow in a systematic
way to achieve the desired results
Why do we need the Selenium Framework?
● Easy code maintenance
● Increase in code re-usage
● Higher code readability
● Reduced script maintenance cost
● Reduced tests time execution
● Reduced human resources
● Easy reporting
Framework
● Linear Scripting Framework is a basic level test automation framework that is in the
form of ‘Record and Playback’ in a linear fashion.
● This type of framework is used to test small-sized applications.
● In the modular testing framework, testers create test scripts module wise by breaking
down the complete application under test into smaller, independent tests.
● The data-driven test automation framework is focused on separating the test scripts
logic and the test data from each other.
● It allows us to create test automation scripts by passing different sets of test data.
● In Keyword-driven framework, we use a table format to define keywords or action
words for each function or method that we would execute.
● It performs automation test scripts based on the keywords specified in the excel sheet.
● Hybrid Test automation framework is the combination of two or more frameworks
mentioned above. It attempts to leverage the strengths and benefits of other
frameworks for the particular test environment it manages. Most of the teams are
building this hybrid driven framework in the current market.
● Behavior Driven Development framework is to create a platform that allows everyone
(such as Business Analysts, Developers, Testers, etc,) to participate actively. It requires
increased collaboration between Development and Test Teams. It doesn’t require the
users to be acquainted with a programming language. We use non-technical, natural
language to create test specifications. Some of the tools available in the market for
Behavior Driven Development is JBehave, Cucumber, etc.,
Data Driven Framework
Git Life Cycle
Git Commands
Interview Questions
What is the difference between Soft Assertion and Hard
Assertion?
● Hard Assertions when failed will stop the execution and the
remaining steps in the Automation code won't be executed
● Soft Assertions when failed, will still continue the execution and
hence the remaining steps in the Automation code will be
executed
What are the different types of Exceptions you have faced in
Selenium WebDriver?
● NoSuchElementException
● NoSuchWindowException
● NoSuchFrameException
● NoAlertPresentException
● InvalidSelectorException
● ElementNotInteractableException
● NoSuchSessionException
● TimeoutException
What is Implicit Wait / Explicit Wait in Selenium WebDriver?
● Implicit Wait is a Global Wait which waits for all the Web
Elements equally
● Unlike Thread.Sleep, Implicit Wait waits for the Web Elements
dynamically
● driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
● Explicit Wait - Instead of waiting for all the Web Elements in the
automation script, Explicit wait will wait only for the specific web
element
● WebDriverWait wait = new WebDriverWait(driver, 5);
● WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkTe
xt("Facebook")));
● element.click();
Fluent Wait in Selenium WebDriver?
● Advanced version of Explicit Wait
How to achieve database testing in Selenium?
● https://drive.google.com/file/d/1YhPjrRcLymFbenSfbREL8PZIGy8JLl
nS/view
● To connect database syntax - Connection con =
DriverManager.getConnection(dbUrl,username,password);
What is JavascriptExecutor and in which case JavascriptExecutor
will help in Selenium automation?
● JavascriptExecutor is a predefined interface in Selenium WebDriver
API
We generally use JavascriptExecutor in Selenium WebDriver,
1. When the normal click() is not working

2. Selenium WebDriver don't have the capability to scroll the page


3. And many more cases, where Selenium WebDriver's default things
are not going to help
How to scroll web page up and down using Selenium WebDriver?
● JavascriptExecutor jse = (JavascriptExecutor) driver;
● jse.executeScript("window.scrollBy(0,300);");
● jse.executeScript("window.scrollBy(0,-300);")
How to upload a file in Selenium WebDriver?
● sendKeys() can be used to upload a file in Selenium WebDriver
● Uploading the files from a workspace folder instead of local folder
Here is the code:
● driver.findElement(By.id("upload")).sendKeys("Path of the file");
BDD Framework - Cucumber
What is Cucumber?
● A cucumber is a software tool that supports behavior-driven development
● Cucumber use Gherkin language as a parser
● It supports various languages like Java, JavaScript, Ruby & Python
● Cucumber is free to use
What is BDD?
● BDD includes test case development based on the behavior of software
functionalities
● BDD is written in simple English language statements, not in a typical
programming language
● BDD improves communication between technical and non-technical teams
and stakeholders
Installation
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>4.2.2</version>
</dependency>

Installation
What is Gherkin?
● Gherkin is a language that developers use to define tests in Cucumber. Since
this language uses plain English, it’s meant to describe use cases for a
software system in a way that can be read and understood by almost anyone
Gherkin explanation
● Feature - The feature file starts with the keyword Feature. Under feature,
you can mention the feature name which is to be tested
● Scenario - Each scenario starts with a keyword Scenario
● There can be one or more scenarios in a feature file
● Given - It is used to define the precondition in our test
● When - It is used to define an action
● And - It is used to connect two statements and provides the logical AND
condition between any two statements
● Then - It is used to define the final outcome or for validation
● But - It defines the negative assertion
Feature file sample

Step definition file sample
Runner file sample
Hooks
What are Hooks?
Hooks are blocks of code that can run at various points in the Cucumber
execution cycle.
They are typically used for setup and teardown of the environment before and
after each scenario.
Types of hooks
Scenario hooks
@Before
@After
Step hook
@BeforeStep @AfterStep
Action items
● Learn above Extent And Allure Reporting
● Learn about Log4j - Logging mechanism
● Learn Source code management tool - GIT
● Learn Selenium 4 features
● Learn different Frameworks ( BDD)
● Have your linkedin Profile upto date
● Have your Git repository filled with your all practical coding
● Learn about SQL
● Learn about what is API and how it has been testing (API testing) -
The most needed and demand skill
Any Question?

You might also like