You are on page 1of 97

Selenium with Java

© Atos|Syntel Inc. - For internal use

1
TestNG Framework Selenium Component

TestNG Annotation Selenium IDE

Selenium Selenium WebDriver

Selenium Features Alert Handling

2 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Agenda

Window Handling

Action Class

JSExecutor

Screenshot

3 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


TestNG Framework
TestNG Framework

▶ TestNG is an advance framework designed in a way to leverage the


benefits by both the developers and testers. For people already using
JUnit, TestNG would seem no different with some advance features.
With the commencement of the frameworks, JUnit gained an
enormous popularity across the Java applications, Java developers
and Java testers, with remarkably increasing the code quality.

5 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Features of TestNG

 Support for annotations


 Support for parameterization
 Advance execution methodology that do not require test suites to be created
 Support for Data Driven Testing using Dataproviders
 Enables user to set execution priorities for the test methods
 Supports threat safe environment when executing multiple threads
 Readily supports integration with various tools and plug-ins like build tools
(Ant, Maven etc
 Facilitates user with effective means of Report Generation using ReportNG

6 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


TestNG versus JUnit

▶ There are various advantages that make TestNG superior to JUnit. Some of

them are:

 Advance and easy annotations

 Execution patterns can be set

 Concurrent execution of test scripts

 Test case dependencies can be set

7 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


TestNG Installation in Eclipse

Follow the below steps to TestNG Download and installation on eclipse:

•Step 1: Launch eclipse IDE -> Click on the Help option within the menu -> Select
“Eclipse Marketplace..” option within the dropdown.
•Step 2: Enter the keyword “TestNG” in the search textbox and click on “Go”
button as shown below.
•Step 3: As soon as the user clicks on the “Go” button, the results matching to
the search string would be displayed. Now user can click on the Install button to
install TestNG.

8 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


TestNG installation in Eclipse

• Step 4: As soon as the user clicks on the Install button, the user is prompted
with a window to confirm the installation. Click on “Confirm” button.

• Step 5: In the next step, the application would prompt you to accept the
license and then click on the “Finish” button.

• Step 6: The installation is initiated now and the progress can be seen as
following:

9 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


TestNG installation

10 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


TestNG Annotation
Test NG Annotation Description

 @BeforeSuite
▶ The annotated method will be run only once before all tests in this suite
have run.
 @AfterSuite
▶ The annotated method will be run only once after all tests in this suite
have run.
 @BeforeClass
▶ The annotated method will be run only once before the first test method
in the current class is invoked.
 @AfterClass
▶ The annotated method will be run only once after all the test methods in
the current class have run.

12 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Test NG Annotation Description
 @BeforeTest
▶ The annotated method will be run before any test method belonging to
the classes inside the <test> tag is run.
 @AfterTest
▶ The annotated method will be run after all the test methods belonging
to the classes inside the <test> 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.
13 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use
Test NG Annotation Description

 @BeforeMethod
The annotated method will be run before each test method.
 @AfterMethod
The annotated method will be run after each test method.
 @DataProvider
Marks a method as supplying data for a test method. The annotated method
must return an Object[ ][ ], where each Object[ ] can be assigned the
parameter list of the test method. The @Test method that wants to receive
data from this DataProvider needs to use a dataProvider name equals to the
name of this annotation.

14 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Test NG Annotation Description

 @Factory
Marks a method as a factory that returns objects that will be used by
TestNG as Test classes. The method must return Object[ ].
 @Listeners
Defines listeners on a test class.
 @Parameters
Describes how to pass parameters to a @Test method.
 @Test
Marks a class or a method as a part of the test.

15 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Example
let’s create a sample class whose methods will be unit-tested using testNG.
Below is the sample class we will use in this example.
public class Calculator {
public double add(double a, double b){
return a+b;
}

public double subtract(double a, double b){


return a-b;
}

public double multiply(double a, double b){


return a*b;
}
}

16 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Example
▶ Nothing special about this Calculator class, which provides methods for
common arithmetic operations. We will unit test each of these
methods.

package com.websystique.testng;
public class TestCalculator {
Calculator calculator;
@BeforeClass
public void beforeClass(){
System.out.println("@BeforeClass: I run only once, before first test
start.");
calculator = new Calculator();
}

17 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Example
@AfterClass
public void afterClass(){
System.out.println("@AfterClass: I run only once, after all tests have
been done.\n");
calculator = null;
}
@BeforeMethod
public void beforeEachTestMethod(Method method){
System.out.println("\n@BeforeMethod: I run before each test method. Test to be
executed is : "+method.getName());
}

18 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Example

@AfterMethod
public void afterEachTestMethod(Method method){//Parameter are optional
System.out.println("@AfterMethod: I run after each test method. Test
just executed is : "+method.getName()+"\n");
}
@Test
public void testAdd(){
System.out.println("@Test add");
Assert.assertEquals(calculator.add(2, 3), 5.0);
}

19 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Example

@Test
public void testSubtract(){
System.out.println("@Test subtract");
Assert.assertTrue(calculator.subtract(5, 3) > 1, "Subtract test failed");
}
@Test
public void testMultiply(){
System.out.println("@Test multiply");
Assert.assertEquals(calculator.multiply(5, 3) , 15.0);
}

20 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Suit Test

▶ In TestNG, we cannot define a suite in testing source code, but it is


represented by one XML file, as suite is the feature of execution. It also allows
flexible configuration of the tests to be run. A suite can contain one or more
tests and is defined by the <suite> tag.
▶ <suite> is the root tag of your testng.xml. It describes a test suite, which in
turn is made of several <test> sections.
▶ Example:
▶ 1.create two classes with name Test1 ,Test2 whose methods will be unit-
tested using testing.
▶ 2.Configure the suit test in an Testng.xml file.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

21 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Suit Test

<suite name = "Suite1">


<test name = "exampletest1">
<classes>
<class name = "Test1" />
</classes>
</test>
<test name = "exampletest2">
<classes> <class name = "Test2" />
</classes>
</test>
</suite>

22 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Test Ignore

▶ If a test method is annotated with @Test(enabled = false), then the test case
that is not ready to test is bypassed.
▶ Example:
Class Demo
{
String name=“admin”;
@Test(enabled = false)
public void testLogin()
{
System.out.println("Inside Login");
Assert.assertEquals(name,”admin”);
}
}
23 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use
Group Test

▶ Group test is a new innovative feature in TestNG, which doesn’t exist in JUnit
framework. It permits you to dispatch methods into proper portions and
perform sophisticated groupings of test methods.
▶ Not only can you declare those methods that 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.

24 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Dependency Test

▶ Sometimes, you may need to invoke methods in a test case in a particular


order, or you may want to share some data and state between methods. This
kind of dependency is supported by TestNG, as it supports the declaration of
explicit dependencies between test methods.
▶ TestNG allows you to specify dependencies either with −
 Using attribute dependsOnMethods in @Test annotations, OR.
 Using attribute dependsOnGroups in @Test annotations.
▶ Example:
public class Demo2 {
@Test
public void test_login() {
System.out.println("login tested");
}
25 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use
Dependency Test

@Test(dependsOnMethods={"test_login"})
public void test_compose(){
System.out.println("Compose tested");
}
}

26 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Parameterized Tests

 Another interesting feature available in TestNG is parametric testing.


 Parameterized tests allow developers to run the same test over and over
again using different values.
 TestNG lets you pass parameters directly to your test methods in two different
ways −
• With testng.xml
• With Data Providers

27 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Parameterized Test

▶ Example:
public class ParameterizedTest1
{
@Test @Parameters("myName")
public void parameterTest(String myName)
{
System.out.println("Parameterized value is : " + myName);
}
}

28 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Parameterized Test

Testng.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<parameter name = "myName" value="manisha"/>
<classes>
<class name = "ParameterizedTest1" />
</classes>
</test>
</suite>

29 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Passing Parameters with Dataproviders

▶ When you need to pass complex parameters or parameters that need to be


created from Java (complex objects, objects read from a property file or a
database, etc.), parameters can be passed using Dataproviders.
▶ A Data Provider is a method annotated with @DataProvider. This annotation has
only one string attribute: its name. If the name is not supplied, the data
provider’s name automatically defaults to the method’s name. A data provider
returns an array of objects.
▶ Example:
▶ 1.Create a class Calculator.java
▶ public class Calculator {
▶ public int add(int a,int b){
▶ return a+b;
▶ }

30 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Passing Parameters with Dataproviders

▶ 2. Create Test Case Class


public class TestCase {
Calculator calc = null;
@BeforeClass
public void create_calcinstance(){
calc= new Calculator();
}
@Test(dataProvider = "dpAdd")
public void test_Add(int a, int b, int Expected_result) {
Assert.assertEquals(calc.add(a,b),Expected_result,"Actual result not
equal to Expected result");
}

31 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Passing Parameters with Dataproviders

▶ @DataProvider (name= "dpAdd")


public Object [][] getData(){
Object[][] table = new Object[][]{
{10,30,40},
{50,10,80},
{20,20,40},
{40,50,120},
{34,20,54},
{30,40,234} };
return table;
}

32 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Passing Parameters with Dataproviders

@AfterClass
public void close_calcinstance(){
calc=null;
}
}

33 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium
What is Selenium

▶ Selenium is a free (open-source)


▶ used for automating web-based applications UI.
▶ automation across different browsers, platforms.
▶ use multiple programming languages like Java, C#, Python etc to create
Selenium Test Scripts.
▶ Using Selenium, we can automate the functional tests.
▶ easily integrate them with Maven, Jenkins, and other build automation and
continuous integration tools.
▶ Testing done using the Selenium testing tool is usually referred to as Selenium
Testing.

35 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium History

▶ Selenium was originally developed by Jason Huggins in 2004 as an internal


tool at ThoughtWorks
▶ Paul Hammant joined the team and steered the development of the second
mode of operation that would later become 'Selenium Remote Control' (RC).
▶ In 2007, Simon Stewart at ThoughtWorks developed a superior browser
automation tool called WebDriver.
▶ In 2009, after a meeting between the developers at the Google Test
Automation Conference, it was decided to merge the two projects, and call the
new project Selenium WebDriver, or Selenium 2.0.
▶ In 2008, Philippe Hanrigou (then at ThoughtWorks) made 'Selenium Grid',
which provides a hub allowing the running of multiple Selenium tests
concurrently on any number of local or remote systems, thus minimizing test
execution time.

36 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium Feature
Selenium Feature

▶ Selenium is a free (open source) automated testing suite for web applications
across different browsers(IE 6/7, Firefox, Opera, Safari 2.0+) and platforms
(Windows, Linux, and Macintosh).

▶ Selenium allows scripting in several languages like Java, C#, PHP and Python.

▶ Selenium is not just a single tool but a suite of software's, each catering to
different testing needs of an organization. It has four components.

38 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium Component
Selenium Component

40 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium Component

▶ Selenium IDE
– A Firefox extension that can automate the browser through a record-and-
playback feature.

– To further increase the speed in creating test cases

▶ WebDriver
– when browsers and web applications were becoming more powerful and
more restrictive with JavaScript programs like Selenium Core.

– It was the first cross-platform testing framework that could control the
browser from the OS level.

41 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium Component

▶ Selenium Remote Control (Selenium RC)

– Selenium RC is a server, written in java, that accepts commands for the


browser via HTTP.

– During the Early Stages testers using Selenium Core had to install the
whole application under test and the web server on their own local
computers

– Later ThoughtWork’s, decided to create a server that will act as an HTTP


proxy to “trick” the browser into believing that Selenium Core and the web
application being tested come from the same domain.

42 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium Component

▶ Selenium Grid
– To address the need of minimizing test execution times as much as
possible.

– Initially called the system “Hosted QA.”

– It was capable of capturing browser screenshots during significant stages,


and also of sending out Selenium commands to different machines
simultaneously

43 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium IDE
Birth Of Selenium IDE

▶ Shinya Kasatani of Japan created Selenium IDE, a Firefox extension that can
automate the browser through a record-and-playback feature.
▶ He came up with this idea to further increase the speed in creating test cases.
▶ He donated Selenium IDE to the Selenium Project in 2006.

45 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium IDE in Chrome

46 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium IDE in Chrome

47 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium IDE in Chrome

48 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium IDE in chrome

49 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Creating Selenium IDE Tests

▶ Steps are involved in creating Selenium tests using IDE:


– Recording a test
– adding commands in
– Saving the recorded test
– Saving the test suite
– Executing the recorded test
– Export the test script

50 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


What is Selenese ?

▶ Selenese is the language used to write Selenium Commands.


▶ These Selenese commands are then used to test web-applications.
▶ Based on the HTML tags of the UI elements, one can check their existence.
▶ Commands help Selenium understand what actions or operations to perform.

51 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Classification of Selenium Commands

▶ Selenium commands are mainly categorized into three types: Actions – Help
manipulate or change the state of applications (e.g. click on some link or
select an option from a page).
▶ Accessors – Enable verification and storage of the application state (e.g.
consider command “storeTextPresent” – if the text is found on the page, then
it stores True else stores false).
▶ Assertions – Help compare expected and actual results. They act like
checkpoints and if both the values are equal, only then the test case passes or
else it fails. Thus, Assertions help verify whether the state of the application
after executing the test case conforms to the desired state (e.g. VerifyText,
waitForPageToLoad).

52 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Classification of Selenium Commands

– Assertions have three modes:


• Assert
• Verify
• WaitFor

53 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium - IDE Verification Points

▶ The test cases that we develop also need to check the properties of a web
page.
▶ It requires assert and verify commands.
▶ There are two ways to insert verification points into the script.
▶ To insert a verification point in recording mode, "Right click" on the element
and choose “Insert New Command“. The mostly used verification commands
– verifyElementPresent
– assertElementPresent
– verifyElementNotPresent
– assertElementNotPresent
– verifyText
– assertText

54 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium - IDE Verification Points

– verifyChecked
– assertChecked
– verifyAlert
– assertAlert
– verifyTitle
– assertTitle
– verifyAlert
– assertAlert
– verifyTitle
– assertTitle

55 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium IDE - Synchronization Points

▶ During script execution, the application might respond based on server load,
hence it is required for the application and script to be in sync. Given below
are few a commands that we can use to ensure that the script and application
are in sync.
– waitForAlertNotPresent
– waitForAlertPresent
– waitForElementPresent
– waitForElementNotPresent
– waitForTextPresent
– waitForTextNotPresent
– waitForPageToLoad
– waitForFrameToLoad

56 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Selenium WebDriver
Selenium WebDriver

▶ WebDriver is a web automation framework that allows you to execute your


tests against different browsers, not just Firefox (unlike Selenium IDE).
▶ WebDriver also enables you to use a programming language in creating your
test scripts
▶ Following programming languages are supported by WebDriver
– Java
– .NetP
– Perl
– Ruby
– Python
– PHP

58 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


WebDriver API Commands and Operations

▶ Creating browser instance for firefox.


– WebDriver driver= new FirefoxDriver();
▶ If you are using firefox 47 and so on then use Geckodriver
▶ Creating browser instance using Geckodriver
– System.setProperty("webdriver.firefox.marionette","C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

59 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


WebDriver Commands

▶ Browser Commands
▶ Navigation Commands
▶ WebElement Commands
▶ Switch Commands
▶ Wait Commands

60 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Browser Commands

▶ Get Command
get(String arg0) : void – This method Load a new web page in the
current browser window. Accepts String as a parameter and returns
nothing.
Command – driver.get(appUrl);
▶ Get Title Command
getTitle() : String – This method fetches the Title of the current page. Accepts
nothing as a parameter and returns a String value.
Command – driver.getTitle();

61 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


▶ Get Current URL Command
getCurrentUrl() : String – This method fetches the string representing
the Current URL which is opened in the browser. Accepts nothing as
a parameter and returns a String value.
Command – driver.getCurrentTitle();
▶ Get Page Source Command
getPageSource() : String – This method returns the Source Code of the
page. Accepts nothing as a parameter and returns a String value.
Command – driver.getPageSource();

62 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Browser Commands

▶ Closing Browser
– close() : void – This method Close only the current window the WebDriver
is currently controlling. Accepts nothing as a parameter and returns
nothing.
– driver.close();
▶ Closing Browser and other all other windows associated with the driver
– quit() : void – This method Closes all windows opened by the WebDriver.
Accepts nothing as a parameter and returns nothing.
– driver.quit();

63 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Browser Commands

▶ Moving Between Windows and Frames


Some web applications have many frames or multiple windows. WebDriver
supports moving between named windows using the “switchTo” method.
▶ Syntax:
driver.switchTo().window( "windowName" );
driver.switchTo().frame( “frameName" );

64 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Browser Navigation Commands

▶ Browser Navigation
▶ Syntax :
driver.navigate().to( "http://www.example.com" );
▶ “navigate” interface also exposes the ability to move backwards and forwards in your
browser’s and refresh the current page
▶ Syntax :
driver.navigate().to("www.amazon.com");
driver.navigate().forward();
driver.navigate().back();
driver.navigate().refresh();

65 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


WebElement Commands

▶ WebElement represents an HTML element. HTML documents are made up by


HTML elements. HTML elements are written with a start tag, with an end tag,
with the content in between
– <p> My first HTML paragraph. </p>
▶ to get the WebElement object write the below statement:
– WebElement element = driver.findElement(By.id(“UserName“));

Clear Command
– clear( ) : void – If this element is a text entry element, this will clear the
value. This method accepts nothing as a parameter and returns
nothing.
– Command – element.clear();

66 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


– WebElement element = driver.findElement(By.id("UserName"));
– element.clear();
▶ IsSelected Command
– isSelected( ) : boolean – Determine whether or not this element is
selected or not. This accepts nothing as a parameter but returns
boolean value(true/false).
– Command – element.isSelected();

67 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


WebElement Commands

▶ Submit Command
– submit( ) : void– This method works well/better than the click() if
the current element is a form, or an element within a form. This
accepts nothing as a parameter and returns nothing.
– Command – element.submit();
▶ SendKeys Command
– sendKeys(CharSequence… keysToSend ) : void – This simulate typing into
an element, which may set its value. This method accepts CharSequence as
a parameter and returns nothing.
– Command – element.sendKeys(“text”);

68 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


WebElement Commands

▶ Click Command
– click( ) : void – This simulates the clicking of any element. Accepts nothing
as a parameter and returns nothing.
– Command – element.click();
▶ IsEnabled Command
– isEnabled( ) : boolean – This determines if the element currently is Enabled
or not? This accepts nothing as a parameter but returns boolean
value(true/false).
– Command – element.isEnabled();

69 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


What Are Browser Elements?

▶ Elements are the different components that are present on web pages. The
most common elements we notice while browsing are:
– Text boxes
– Buttons
– Images
– Hyperlinks
– Radio buttons/ Checkboxes
– Text area/ Error messages
– Drop down box/ List box/ Combo box
– Web Table/ HTML Table
– Frame

70 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


findElement(), findElements()

▶ There are various techniques by which the WebDriver identifies the form
elements based on the different properties of the Web elements like
– By ID
– By Name
– By Link Text
– By CSS
– By Xpath
▶ Web Driver provides the following two methods to find the elements.
▶ findElement() – finds a single web element and returns as a WebElement
object.
▶ findElements() – returns a list of WebElement objects matching the locator
criteria

71 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Alert Handling
Alert

▶ The pop up window that comes up on screen is called Alert

▶ Alerts are different from regular windows. The main difference is

that alerts interrupts the flow.

▶ They will not allow any action on the underlying webpage if they

appear

73 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Types of Alert

▶ Java script provides mainly following three types of alerts:

1. Simple alert

2. Confirmation alert

3. Prompt alert

74 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


How to handle Alerts?

▶ It can be handled using the Alert interface under the package

org.openqa.selenium.Alert package.

▶ Alerts can be handled in different ways using these methods:


• accept() To accept the alert
• dismiss() To dismiss the alert
• getText() To get the text of the alert
• sendKeys() To write some text to the alert

75 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Example

driver.findElement(By.id("alertButton")).click();
Alert simpleAlert = driver.switchTo().alert();
simpleAlert.accept();

76 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Window Handling
Window Handling

▶ While working with any web application there are many scenarios

where we would need to switch the control between multiple

windows, for these situations, we should use webdriver API’s built-

in window methods.

78 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Window Handling in Selenium

▶ Every window has a unique handle. Handle means a specific identifier that

represents its window. We can manage the windows with their handles.

– driver.getWindowHandle() – gets the current window’s handle

– driver.getWindowHandles() – gets all windows handles

– driver.switchTo().window(String handle) – used to switch to

the target window by using its handle.

79 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


How to Manage Windows in Selenium?

▶ Web driver provides us below methods to manage windows. We can control the size and
position of the current window with the following methods.

Driver.manage.window()

.maximize() – It maximizes the current window.

.getSize() – It returns the size of the current window.

.setSize() – It sets a new size to current window.

.getPosition() – It returns current position in term of x,y coordinates.

.setPosition() – It moves the current window around

80 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Example

// Get the current window's handle and write to the console window. It must be first
window handle.
System.out.println("Current Window Handle:"+
driver.getWindowHandle() +"\n");
//Get all window handles and hold them in a list.
Set<String> windowHandles = driver.getWindowHandles();
List<String> windowHandlesList = new ArrayList<>(windowHandles);
//Set to List Conversion

81 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Action Class
Action Class

▶ Actions like clicking a button, entering a keyword in the search bar are prime

examples of how we use a mouse or keyboard.

▶ These interactions are done through the mouse and the keyboard can be automated

by using the Actions class in Selenium.

▶ The actions that can be performed in a browser are broadly classified into two

categories namely-

• Mouse actions

• Keyboard actions

83 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Mouse Actions

▶ The various mouse actions that are provided by the Actions class are:

• click() – clicks at the current location

• doubleClick() – performs a Double click at the current mouse location

• contextClick() – performs a Right click at the current mouse location

• dragAndDrop(WebElement source, WebElement target) – drags an element from the


source location and drops in target location

• moveToElement(WebElement target) – moves to the target element

84 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Keyboard Actions

▶ The various keyboard actions that are provided by the Actions class are:

• keyUp(WebElement target, java.lang.CharSequence key) – performs a


key release after focusing on the target element

• keyDown(WebElement target, java.lang.CharSequence key) – performs


a key press after focusing on the target element

• sendKeys(WebElement target, java.lang.CharSequence… keys) – types


the value.

85 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Build() & perform()

▶ Use the perform() method when executing the Action object


▶ The build() method is always the final method used so that all the listed actions will be compiled into a
single step.

Action seriesOfActions = builder


.moveToElement(txtUsername)
.click()
.keyDown(txtUsername, Keys.SHIFT)
.sendKeys(txtUsername, "hello")
.keyUp(txtUsername, Keys.SHIFT)
.doubleClick(txtUsername)
.contextClick()
.build();

seriesOfActions.perform() ;

86 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Example

//create an object for the Actions class and pass the driver argument

Actions action= new Actions(driver);

//pass the product name that has to be searched in the website

action.sendKeys (element, ”Testing”),build().perform();

87 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


JSExecutor
JSExecutor in Selenium
▶ JavaScriptExecutor is an interface provided by
Selenium Webdriver, which presents a way to
execute JavaScript from Web driver.

▶ This interface provides methods to run JavaScript


on the selected window or the current page.

▶ JavaScriptExecutor is an interface which is available


for all the languages that support the selenium
framework
Why ?
89 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use
JSExecutor Methods
▶ executeScript

• This method executes JavaScript in the context of the currently


selected window or frame in Selenium. The script will be executed
as the body of an anonymous function.

▶ executeAsyncScript

• This method executes an asynchronous snippet of JavaScript in


the context of the currently selected window or frame in Selenium

• The major difference between executeScript and


executeAsyncScript is that the script invoked using the
90 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use
Example

js.executeScript("document.getElementById('enter
element id').click();");

//or
js.executeScript("arguments[0].click();", okButton);

91 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Screenshot
Screenshot in Selenium
▶ Capturing the screen while performing certain action for future reference can be achieved
using screenshot

▶ Its very important to take screenshot when we execute a test script.

▶ When we execute huge number of test scripts, and if some test fails, we need to check
why the test has failed.

▶ Syntax:

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

93 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Contd..
▶ Depending on the browser being used, the TakesScreenshot method
can return the following:

• The entire page

• The current open window

• The visible segment of the current frame

• The whole display containing the browser

• The complete content of the HTML element. This essentially refers


to the visible portion of the HTML element.
94 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use
To capture a particular location
in screen
// Convert the screenshot into BufferedImage
BufferedImage fullScreen = ImageIO.read(screenshot);
//Find location of the webelement logo on the page
Point location = logo.getLocation();
//Find width and height of the located element logo
int width = logo.getSize().getWidth();
int height = logo.getSize().getHeight();

//cropping the full image to get only the logo screenshot


BufferedImage logoImage = fullScreen.getSubimage(location.getX(),
location.getY(),width, height);
ImageIO.write(logoImage, "png", screenshot);

//Save cropped Image at destination location physically.


FileUtils.copyFile(screenshot, new
File("C:\\projectScreenshots\\particularElementScreenshot.PNG"));

95 | dd-mm-yyyy | © Atos|Syntel Inc. - For internal use


Questions
Thank you

Atos, the Atos logo, Atos|Syntel are registered trademarks of the Atos group. © 2021
Atos. Confidential information owned by Atos, to be used by the recipient only. This
document, or any part of it, may not be reproduced, copied, circulated and/or
distributed nor quoted without prior written approval from Atos.

You might also like