SlideShare una empresa de Scribd logo
1 de 199
Introduction
• Rishikesh – Trainer’s Profile
• Your introduction
• Name, Total Experience, Tenure in current
organization, Aspiration, Automation exposure
5/5/2021 Selenium Webdriver 2.0 1
Rishikesh – Trainer’s Profile
• Rishikesh has close to 15 years of IT Experience
• Masters in Computer Science from Pune University
• Certifications – PMP, CSQA, CSM, ITIL
• Organizations – Tech Mahindra, Syntel, BMC Software, IBM
• Last designation - Sr. Test Manager in Tech Mahindra
• Handled very large teams - 150 members and worked with product and service industry
• Was part of TCoE, PreSales, Deliver management
• Currently hold a training consultancy – Vedant Consultancy in Pune
• Conducted numerous corporate trainings in Pune, Bangalore, seminars in different colleges.
• Tools Expertise
• Functional Testing
• Selenium WebDriver.20
• UFT (Former name QTP)
• AUTO IT
• WebService API Testing
• SOAPUI
• Performance Testing
• Jmeter
• LoadRunner
• Mobile Testing
• Selendroid
• Appium
• Shell Scripting
5/5/2021 Selenium Webdriver 2.0 2
Pre-Requisite to Learn Selenium
• Programming language concepts
• Basic knowledge of coding – any language
• HTML knowledge – tag identification, Attributes etc.
• XML knowledge for Selenium IDE
• Java Script knowledge for IDE
• Developer’s mindset – How to create/construct
• Java or any Selenium supported language
• Debugging skill
• Learning attitude
• Patience
5/5/2021 Selenium Webdriver 2.0 3
Selenium Learning
*** HAPPY
LEARNING ***
5/5/2021 Selenium Webdriver 2.0 4
FAQ From Beginners
• What is Selenium?
• Selenium is a suite of tools to automate web browsers across many platforms.
• What all browser Selenium supports?
• IE, Chrome, Firefox, Android, iPhone
• What all languages are supported by Selenium?
• Java, C#, Ruby, Python, Perl, PHP
• Is it mandatory to write test script in same language in which software is made?
• No
• Why is Selenium is getting popular in market?
• Open source, wide blogs/forum, Google support
• Is it mandatory to learn Java in depth to master in Selenium?
• No
• What are course contents? What all topics will be covered in the course?
• Can I use IDE component to automate complete product/project?
• How much time would I require to learn Selenium?
• Learning – 1 week
• Intermediate 3 months
• Expertise – 6 months to 1 year
• Practice Practice and Practice is a key to learn any automation tool.
5/5/2021 Selenium Webdriver 2.0 5
Testing All About
• What is testing? Use of Testing?
• Discovering defects and finding enhancement to the product
• Fit for use
• Conformance to the requirement
• What is manual Testing?
• What is Automation Testing?
• Convert manual actions into automated actions with verifications
• Advantages of Automation Testing
• Consistency output: Increased repeatability
• Data sensitive test cases
• Lengthy test cases
• Less time to market
• Support to Browser/OS/Database
• Higher Test coverage
• Various Tools
• Proprietary – QTP/UFT, Rational Robot, SilkTest , Testcomplete, VSTP
• Open source – Selenium, SOAPUI, AUTOIT, Watir,
5/5/2021 Selenium Webdriver 2.0 6
JAVA – Object Oriented Programming
• How to download and install Java?
• Google->Download Java
• Verify if Java is installed: C:programFilesJava folder presence
• What is IDE – Integrated Development Environment?
• What is Eclipse? How to download and install Eclipse?
• Google->Download Eclipse->Eclipse IDE for Java Developers (~212 MB) – 32 or 64 bit windows version
• Eclipse is an exe file, does not need to install
• Double click on Eclipse.exe to open Eclipse
• What is Workspace?
• A work area where test scripts are stored through Eclipse
• Open Eclipse
• Project Explorer, Java Perspective,
• Increase font size
• Go to Windows->Preferences->General->Appearances->Colors and fonts
• File->New Project->Java Project-> <project name>
• Expand project folder in Solution Explorer and find SRC folder (Source) contains all Java scripts
• Right click on Project name in Solution Explorer->Java Properties – finds all project’s properties
• Check project on disk system
• Create first Java class in Java Project
• Check java class on physical disk system
• Understand first program
• Comments – // or /* */ why to have comments in program?
• Java case sensitive language
• Auto suggestion available in IDE – Eclipse – Advantage over writing program in notepad
• Run program 1. right click on class file in solution explorer and run as Java application
• 2. Run by pressing right triangle
5/5/2021 Selenium Webdriver 2.0 7
JAVA – Object Oriented Programming
• Short cut to write syso + Control + spacebar - System.out.println
• Difference between System.out.println and System.out.print
• Extension of java file is .JAVA
• Extension of compile JAVA program is .class (Byte code)
• .class file can be executed on any platform. Windows .class file can be
executed on Unix and vice-versa.
• How to debug a program in Java using Eclipse?
• F8 step by step execution
5/5/2021 Selenium Webdriver 2.0 8
JAVA – Object Oriented Programming
• Open Source
• Sun Microsystem and now Oracle
• Object Oriented Programming
• Inheritance: IS A relationaship, CAR IS A VEHICLE
• Polymorphism
• Overloading
• Overriding
• Encapsulation: HAS A relationship, Building HAS A room
• Class Concept : Skeleton
• Interface Concept: Contract
5/5/2021 Selenium Webdriver 2.0 9
JAVA – Object Oriented Programming
• Case Sensitive and platform independent
• Blue colored words are keyword
• Java dataTypes
• char, int, long, float, double, Boolean
• Comparison operators - >, <, <=, >=, !=
• Logical operators - &&, ||, !
• if condition has to be written in brackets - ()
• Find out greatest of 2 numbers
• Find out greatest of 3 numbers.
• String is inbuilt class in Java
• Control Structure
• If, if else
• Find largest of 2 and 3 numbers
• For
• While
• Arrays
• One dimensional – definition, initialization, printing, length
• Two dimensional -
5/5/2021 Selenium Webdriver 2.0 10
JAVA – Object Oriented Programming
• Array examples using char, int, string
• Drawbacks of array
• What are functions?
• Function parameters – By Value and By Reference
• Function return types
• Local Variable – loop variables, block variables, main
method variables
• Global Variable – Class member
• Meaning of Static variable or method?
• Common memory allocated to static variable or
method
• Object and object reference
• Constructor
5/5/2021 Selenium Webdriver 2.0 11
Constructor
• Used to initialize members (Non static)
• Can have ZERO or more no of parameters
• Automatically called when object is created
• Constructor do not have return type, void and should have
same name as of class
• Example:
• Car c= new Car() // constructor is called when object is created
• Public car()
• { this.model=“BMW”;}
• Constructor Overloading
• Same name with different parameter types
5/5/2021 Selenium Webdriver 2.0 12
Class & Object Concept
Public class Car{
String model;
int price;
Static wheels;
Public static start(){
System.out.println(“Starting : “ + model);
Public static stop(){
System.out.println(“Stopping : “ + model);
}
Public static void main(String args[]) {
Car c1 = new Car();
C1.model=4000000;
C1.model=“Audi”;
Car.wheels=4;
}
5/5/2021 Selenium Webdriver 2.0 13
Model
Price
Start()
Stop()
c1
wheels
Model and price are non static
Wheels is static resides in common memory
& is NOT part of object
Static variable
Inheritance
• Inheritance derives it parents characteristics
Public class Car()
{ int price;
Public void start();{System.out.println(“Starting Car”);
Public void stop();{System.out.println(“Stopping Car”);}
Public class BMW() extends Car
{Public void theftsafety();{System.out.println(“BMW theftsafety…”);
Public void start();{System.out.println(“Starting BMW”); // Overridden method}
• BMW class object reference can access Car class’s global
variable/members and methods.
• Car class is called Super or Parent class
• BMW class is child or sub class.
Car c=new Car();
c.price=10; c.start();
c.theftsafety(); NOT ALLOWED
BMW b=new BMW();b.price=20;b.start();b.theftsafety();
• When object instance is created, constructor of parent and child
class is executed.
5/5/2021 Selenium Webdriver 2.0 14
CAR
BMW
Overridden Method
• Same method is implemented in parent and child class.
• Method implemented in sub class is called overridden
method.
• If BMW class has below method which is already present
in Car class.
• Public void start();{System.out.println(“Starting Car”);}
• Car c = new Car();
• BMW b = new BMW();
• c.start(); This will invoke start method from Car class.
• b.start(); This will invoke start method from BMW class.
5/5/2021 Selenium Webdriver 2.0 15
Object
• Meaning of below object creation?
Car c1 = new BMW();
• C1. can call all methods from Car call (Parent class)
But can not call methods defined only in child class.
• Overridden function can be called from child class.
• c1.start() Overridden method called from BMS
class
• c1.stop() Car method is called
• c1.theftsafty NOT ALLOWED
5/5/2021 Selenium Webdriver 2.0 16
Interface
• Is a abstract class
• Does not have implementation of method
• Declares required methods
• Can not create instance of an interface
• Static function declaration is not allowed
• Initialization of variables is mandatory.
• Variable are static in nature.
• Example
Public interface Bank {
Int minBalance=5000;
Public void transferMoney(); Public void Credit();Public void Debit();}
TestBank.java
Bank b = new Bank(); NOT ALLOWED
HSBCBank.java
Public class HSBCBank implements Bank{
Have to implement all methods in parent class in order to create an instance of inherited class i.e. HSBCBank else it again
becomes interface.
Can we define new method in HSBCBank and call it from testBank.java? NO
TestBank.java
Bank b = new HSBCBank();
b.credit(); b.debit(); b.transfermoney(); System.out.println(b.minBalance);
System.out.println(Bank..minBalance);
5/5/2021 Selenium Webdriver 2.0 17
Package
• Package is nothing but sub folder
• Logical grouping of modules/functionality
• Pgk1
Public class Login()
{ public void adminLogin(){
System.out.println(“Logging as ADMIN user….”);}
• Pgk2
Public class Test{ public static void main(String args[]){
Login l = new Login(); // Require to import Login.adminLogin
L.adminLogin();}
5/5/2021 Selenium Webdriver 2.0 18
Access Modifiers
• Public
• Accessible from everywhere
• Within and outside class
• Within and outside package
• Private
• Accessible from the current package
• Default
• Accessible from the current package
• Protected
• Accessible in current package and all child classes
5/5/2021 Selenium Webdriver 2.0 19
Exception Handling
Try
{
System.out.println(“A”);
Int I = 10/0; // divide by Zero exception raised
System.out.println(“B”);
} catch (Exception e) {
System.out.println(“Error Occurred ” +
e.getMessage());
System.out.println(“C”);
e.printStackTrace(); // prints error
}
• In case of error/exception, control comes to catch block of try-
catch block.
• Output
• A and Error Occurred then C
5/5/2021 Selenium Webdriver 2.0 20
Exception Handling
• Int arr[] = new int[3];
• Arr[3]=12; // will error out ArrayIndexOutofBoundsException
• Instead of try-catch block one can use throws
clause/declaration
• Example
Public static void main(String[] args) throws InterruptedException
{clickLink();}
Public static void clickLink() throws InterruptedException
{loadPage();}
Public static void loadPage() throws InterruptedException
{Thread.sleep(4000L);}
• Throwable is a super class and Error and Exception are child classes.
5/5/2021 Selenium Webdriver 2.0 21
Throw & finally, final clause
• throw new Exception(“Some Exception”);
• Use of throw is to skip test case based on certain condition.
• Finally clause
Executes finally block irrespective of error
Try
{
int i=10/0;
} catch(Exception e) { e.printStackTrace();}
finally{
closeDBConnection();}
• Final int a = 100; // declare as constant
a=200; NOT allowed
5/5/2021 Selenium Webdriver 2.0 22
Collection API
• ArrayList
• Removes drawback of fixed no of elements
• Dynamically growing data structure
• ArrayList contains one data type
• Index starts with ZERO
• ArrayList<String > list = new ArrrayList<String>();
• List.add(“Pune”);
• List.add(“Mumbai”)
• System.out.println(list.get(1)); // extract 1st element i.e.
Mumbai
• List.size() – Returns current size of list
• Print all list elements
• for (int i=0;i<list.size();i++)
• System.out.println(list.get(i));
• Example: Store all links present on web page, Total no of links
are known dynamically.
5/5/2021 Selenium Webdriver 2.0 23
HashTable
• HashTable is inbuilt class
• Dynamically growing data structure
• HashTable has key, value pair
• No index available
• Key in hashtable is unique
• HashTable<String,String> table = new
HashTable<String,String> ();
• table.put(“name”,”Ankit”);
• table.put(“place”,”India”);
• table..put(“profession”,”IT”)
• System.out.println(table.get(“name”)); // Ankit
• System.out.println(table.get(“place”)); /India
• Use HashTable – Test Data can be stored in Selenium.
5/5/2021 Selenium Webdriver 2.0 24
Set
• Data Structure
• Holds multiple values
• Set<String> mySet = new HashSet<String>();
• mySet.add(“India”);
• mySet.add(“UK”);
• mySet.add(“USA”);
• mySet.add(“China”);
• Elements are added
• No index, no order
• Unique value present, no duplicates allowed
• mySet.size() – total elements present
5/5/2021 Selenium Webdriver 2.0 25
Set
Iterator<String> it=mySet.iterator();
While(It.hasNext())
System.out.println(it.next());
5/5/2021 Selenium Webdriver 2.0 26
Selenium Introduction
• What is Selenium?
• Automates web applications across many browsers
• Library by Google (former name Thoughtworks)
• Javascript based automation engine
• Jason Higgins – Thoughtworks 2004 – Core Selenium library
• Simon Stewart – Google a creator of WebDriver
• Selenium 1. 0 – Focused on Remote Control
• Selenium 2.0 – Focused on Webdriver 2.0, released in Jul 2011
• Selenium 3.0 – Extending Webdriver 2.0 to cope up with
Android functionalities – mobile testing, Selendroid and
Appium – To be released in Dec-2015
• Support many Languages
• Java, Python, C#, Ruby, JavaScript
• Supported Browser
• Firefox, IE, chrome, iPhoneDriver, HTMLDriver, AndroidDriver
• OS support
• Windows, Linux, Unix
5/5/2021 Selenium Webdriver 2.0 27
Selenium Introduction
5/5/2021 Selenium Webdriver 2.0 28
Selenium Advantages/Disadvantages
5/5/2021 Selenium Webdriver 2.0 29
Selenium Language Support
5/5/2021 Selenium Webdriver 2.0 30
Selenium Browser Support
5/5/2021 Selenium Webdriver 2.0 31
Selenium OS Support
5/5/2021 Selenium Webdriver 2.0 32
Selenium Framework Support
5/5/2021 Selenium Webdriver 2.0 33
Selenium Overview
• Four components of Selenium
• IDE – Integrated Development Environment
• Selenium Remote Control (RC)
• WebDriver 2.0
• GRID 2
• Basic component - IDE
• Add on to Firefox only
• Record and play
• Remote Control – Deprecated
• Prior version of Selenium WebDriver 2.0
• Need to start Selenium server
• Contain only one class
• GRID 2.0
• Used for parallel test case execution on multiple machines
5/5/2021 Selenium Webdriver 2.0 34
Selenium Webdriver 2.0
• What is WebDriver?
• Is and Interface
• Has many functions/methods like getTitle,get,navigate
• Download and configuration of Selenium JAR files
• Architecture of Selenium
• FirefoxDriver,ChromeDirver implements WebDriver
• Drivers for Firefox, IE, Chrome, Iphone, Android,
HTMLUnitDriver
• Selenium Remote Control (RC)
• Firefox Profile
• Use of Firefox profile
5/5/2021 Selenium Webdriver 2.0 35
FireBug and Firepath Addons
• Firepath and Firebug
• Inspecting elements using Firefox, Chrome, IE
• Identifying webElement/component on webpage
• Locators
• Id,name,class,cssSelector,xpath,LinkText,PartialLinkT
ext
• What is xpath?
• Absolute, partial
• Creating custom xpath
• Handling dynamic xpath
• First Selenium test script
• Difference between close and quit
• Importing webDriver documentation in Eclipse
5/5/2021 Selenium Webdriver 2.0 36
FireBug and Firepath Addons
• What is Firebug and Firepath?
• Add-ons to Firefox browser to find out address of
webelement on webpage
• Xpath, CssSelector useful to find firebug & firepath
• How to download and install Firebug?
• Google download Firebug
• Click on first link and download (Green button
allows you to download Firebug) and install
• Google download Firepath and download(Green button
allows you to download Firebug) and install . Restart
Firefox browser
5/5/2021 Selenium Webdriver 2.0 37
FireBug and Firepath Addons
• You can see bug icon at the right top corner of Firefox browser as below
• How to find out xpath of a webelement?
• Open gmail.com
• Click on bug icon at top right corner of firefox
• Window at bottom will appear as below
5/5/2021 Selenium Webdriver 2.0 38
FireBug and Firepath Addons
• Red color box at button shows xpath of input field
Enter Your email
5/5/2021 Selenium Webdriver 2.0 39
IDE
• What is IDE?
• Integrated Development Environment
• Who should use IDE
• Beginner to understand how Selenium codes
• How various xpaths are formed for a web element
• Advantages of IDE
• Record and play
• Helpful to find IDE if you are not able to customize of generate
xpath using Firebug
• Disadvantages of IDE
• Dynamic xpaths are problematic.
• Modification to existing script is bit difficult
5/5/2021 Selenium Webdriver 2.0 40
IDE
5/5/2021 Selenium Webdriver 2.0 41
IDE Remote Control WebDriver 2.0
Record and Play Need to code in Java Need to Code in Java
Works for Firefox only Works on all browsers Works on all browsers
Applicable to small projects Applicable to large/huge
projects
Applicable to large/huge
projects
Helps to find xpaths Need to find xpaths using
firebug/firepath or customize
Need to find xpaths using
firebug/firepath or customize
Java Script optional Core Java,Ruby,C#,Python
required
Core Java,Ruby,C#,Python
required
Addon to Firefox Selenium Component Selenium component
In Use Deprecated In Use
No programming language
required to record script
Programming langugage
required to code
Programming langugage
required to code
First Component developed Second component developed Latest component developed
Used to create a script to check
production defect
Used to create regression or
functional test case
Used to create regression or
functional test case
Installation of IDE
• Selenium IDE is addon to Firefox browser.
• Go to seleniumhq.org
• Go to Download link
• Check for Selenium IDE section and click on 2.9.0 link
(latest version)
• Click on Install
• Go to Firefox browser
• Click on Tools and check if Selenium IDE option appears
5/5/2021 Selenium Webdriver 2.0 42
IDE
• By default recording mode is on.
• Can directly record user actions by navigating to any website
in Firefox browser.
• Record opening salesforce.com
• Open command – Opens URL in browser
• Click – click on the webelement
• Type – type text into the web element
• clickAndWait – Click and wait
• Save Test – saves HTML document format
• Run the test and see playing back.
• Able to convert manual actions into automated script with
help of IDE.
5/5/2021 Selenium Webdriver 2.0 43
IDE Pros-Cons
5/5/2021 Selenium Webdriver 2.0 44
IDE
• Various Xpaths (Address of webelement) of Login button
• //*[contains(text(),'Login') and @href='https://login.salesforce.com'] ->
(by.xpath)
• id=button-login ->(By.id)
• //a[contains(text(),'Login')] ->(by.xpath)
• css=#button-login -> CssSelector
• //a[@id='button-login'] ->(by.xpath)
• //ul[@id='lang-select']/li[1]/a ->(by.xpath)
• //a[contains(@href, 'https://login.salesforce.com')] ->(by.xpath)
• One webElement can be identified by multiple xpaths
• One unique xpath can not point to more than one webelement
• One xpath (not unique) can point to more than one webelement.
(//ul[2]/li  9 matches on salesforce.com page)
• To convert above xpath to point to unique webelement
• Add tag at the end and/or
• Add attributes to xpath using and condition.
• //ul[2]/li[1]/a[@id='button-login']
5/5/2021 Selenium Webdriver 2.0 45
IDE
• HTML document format of a test case in browser
5/5/2021 Selenium Webdriver 2.0 46
IDE
• Test case to automate webmath.com
• Go www.webmath.com
• Click on
5/5/2021 Selenium Webdriver 2.0 47
IDE
• From the recorded Login test script, remove
clickAndWait command and run the script to get
“Element [//*[id=‘username’] not found error”
• ClickAndWait will wait until the complete page is loaded
upon clicking of the web element. Default wait time in
Selenium is 30 seconds.
• IF element is not found within 30 seconds script will
error out and script will be halted.
• The statement in IDE becomes red wherever error
occurs.
5/5/2021 Selenium Webdriver 2.0 48
IDE
• Double click statement and it will be executed. This is
helpful to debug the script.
• To debug program
• Right click on the statement where you want to halt execution
at run time and click on Toggle Breakpoint
• At run time, after script is stopped at the breakpoint, Step
button will be used to execute one statement at a time.
• Code can be executed line by line to debug any script.
• Speed of test script execution can be made slow using slider.
5/5/2021 Selenium Webdriver 2.0 49
IDE
• How to verify window title using verifyTitle command?
• Insert command after Open command using right click
and Insert.
• In Command input field, type verifyTitle and in target
type title.
• Click on view source page on salesforce.com webpage,
and find title string and paste this string in target field in
IDE.
• Run script and check if script passes
• If you change title in the target field, and run script it will
be failed, but script will not stopped running further
statements.
• Verify statements does not stop test script execution
5/5/2021 Selenium Webdriver 2.0 50
IDE
• How to verify window title using assertTitle command?
• Insert command after Open command using right click and
Insert.
• In Command input field, type assertTitle and in target type
title.
• Click on view source page on salesforce.com webpage, and
find title string and paste this string in target field in IDE.
• Run script and check if script passes
• If you change title in the target field, and run script it will be
failed, and script will be executed further.
• Assert command will halt test case execution and further
statements in the test script will not be executed.
5/5/2021 Selenium Webdriver 2.0 51
IDE
• When to use verifyTitle or assertTitle?
• If you want to stop further test script execution, use assertTitle. If the
error is severe you should use assert else verify.
• There are many verify commands like
• verifyTitle
• verifyText
• verifyValue etc
• Create a script by recording
• Navigate www.webmath.com
• Click on “Quick! I need help with: “ dropdown list
• Enter any number in first input box
• Select mile(s) per hour from next dropdown
• Select kilometer(s) per hour
• Click on Convert button
• You will land on new page having answer for the problem
• Stop recording and see the generated code
5/5/2021 Selenium Webdriver 2.0 52
IDE
• Original script
• Now insert command (right click on selectAndWait command and click
Insert New command)after open command to 1verify if “Go” button is
present or not
• Enter verifyElementPresent in command input field
• Enter xpath of “Go” button as //*[@id='jumpToPage']/div/a/img
• Now click on type command and right click to insert new command
• Enter assertElementPresent in command input field
• Enter //*[@id='d-
childMainContLeft']/div[2]/table/tbody/tr/td[2]/font/b/form/center/p[3]/in
put[1] in target input field.
5/5/2021 Selenium Webdriver 2.0 53
IDE
• So the final script will look like this
• Run the script, it will be passed.
• Change title and suffix 1 to title in target input field
• Run the script verifyElementPResent will error out but script will run
completely and test case result will be failed in Log.
• The statement which was failed will be shown in red color.
• Now revert title back to original by removing suffix 1
• Add suffix 1 to xpath of assertElementPresent command
• Run the script and script will failed at assertElementPresent command
and will halt without executing further statements and test case result
shown in Log will be failed.
5/5/2021 Selenium Webdriver 2.0 54
IDE
• Passed test result as below
5/5/2021 Selenium Webdriver 2.0 55
IDE
• Add last command as verifyText in command input
• Target is //html/body/font/font/font/center
• Value is You want to convert 5 mile(s) per hour to
kilometer(s) per hour. Here's how:
• Run test script and see it should be passed.
• Final test script looks like
5/5/2021 Selenium Webdriver 2.0 56
IDE
• Customize commands in IDE using extensions
• Control loops – if, while can be written with the help of extension in
IDE.
• Where to get extensions?
• Seleniumhq.org->Documentation->Selenium IDE->Sequence of Evaluation and
Flow Control ->goto_sel_ide.js extension->page-
>github.com/73rhodes/sideflow->Download.zip
• Save it in a folder
• Unzip folder
• Slideflow.js is the only required java script (.js) file
• In IDE, go to Tools->Options->Browse-> Provide the file name Slideflow.js
• Close IDE using File->Exit and restart
• Now command field should have while command present in dropdown list.
• What is salesforce.com website
• Login
• Create Lead for potential customers
5/5/2021 Selenium Webdriver 2.0 57
IDE
• Variable concept in IDE
• Command Target Value Comment
• store 100 b Store b = 1000
• echo ${b} Display 1000
• echo Value of b = ${b} Display Value of b=1000
• echo javascript{storeVars[‘b’]} Display 1000
• Store javascript(storeVars[‘b’]) d store value of b to d i.e. 1000
• echo ${d} Display 1000
• storeEval storedVars[‘b’] e Store e=b, e will have 1000
• echo ${e} display e as 1000
• storeEval new Number(storedVars['b'])+10 f
• echo ${f} display f as 1010
5/5/2021 Selenium Webdriver 2.0 58
IDE
• Parameterization using XML files in IDE
5/5/2021 Selenium Webdriver 2.0 59
Locators
• What is locator?
• Locator helps to identify element on a webpage.
1. id
2. linktext
3. partialLinkText
4. name
5. tagName
6. className
7. cssSelector
8. Xpath
Priority usage of locator:
1. Id is the fastest way to locate web element
2. Xpath
3. cssSelector in case of IE and chrome
Examples are in Notes section
5/5/2021 Selenium Webdriver 2.0 60
Xpath
• Xpath is the address of a webelement
• Syntax - //*[@attribute=‘attribute value’]
• Absolute xpath
• Full xpath starts with html/body/
• Identify web element Username on gmail.com
• html/body/div/div[2]/div/div/form/div[1]/div/div/div/div/inp
ut[1]
• Identify web element Next button on gmail.com
• //html/body/div/div[2]/div[2]/div/form/div/div/input[@value
='Next']
• Partial xpath
• Part of absolute xpath, locates a unique element
• Identify web element Username on gmail.com
• //input[@value='Next']
• Identify web element Next button on gmail.com
• //input[@value='Next']
5/5/2021 Selenium Webdriver 2.0 61
More example on Xpaths
• Identify link “Need Help” on gmail.com
• //*[@id='gaia_firstform']/div/a
• and condition
• //input[@id=‘Email’ and name=‘Email’] - gmail.com
• Or condition
• Functions
• Contains, starts-with
• //*[starts-with(@id,’yui_3_4’)]/ul/li[1] – yahoo.com
autosuggestion
5/5/2021 Selenium Webdriver 2.0 62
cssSelector
• CSS stands for Cascading Style Sheets
• CSS defines how HTML elements are to be displayed
• Are comparatively has fast performance especially in IE and Chrome
browser
• Syntax - *[id=‘id value’]
• *[id=‘Email’] – gmail.com
• input[id=‘Email’] - gmail.com
• Example
• Driver.findElement(By.cssSelector(“input[id=‘Email’]”)).sendKeys(“AAAA”);
• input[id=‘Email’][name=‘Email’] - gmail.com
• div[class=‘product –info mail’] p – gmail.com
• #passwd – same as id=passwd in gmail.com
• Example
• driver.findElement(by.cssSelctor(“#passwd”)).sendKeys(“AAA”);
• More explanation in Notes section
5/5/2021 Selenium Webdriver 2.0 63
cssSelector
• Input[name^=‘Ema’] – find element whose name
starts with Ema
• Input[name$=‘ail’] – find element whose name
ends with ail
• Input[id*=‘ai’] – find element whose name contains
with ai
5/5/2021 Selenium Webdriver 2.0 64
cssSelector
• //input[starts-
with(@id,’yui_3_4_0_1_136255’)/ul/li[1]/a – yahoo.com
search field
• Example
• Driver.get(http://yahoo.com”);
• Driver.findElement(By.xpath(“//input[@id=‘p_13838465-
p’]”))/sendKeys(“Hello”);
• Thread.sleep(4000L);
• String text = driver.findElement(By.xpath(“//*[starts-
with[@id,’yui_3_4_0_1_136255’)/ul/li[1]/a])
• System.out.println(text);
5/5/2021 Selenium Webdriver 2.0 65
Exercise
• Read properties file
• Browser=chrome
• Based on browser key open browser
• Open gmail.com
• Enter user and password
• Login to gmail.com
5/5/2021 Selenium Webdriver 2.0 66
GUI Controls
• GUI Controls/web Elements on Webpage and its
operations
5/5/2021 Selenium Webdriver 2.0 67
Control Operations
Input Input value, read value, clear value
Label Read text
Drop Down List Select Single element, Read All elements, Clear value, find
total no of elements
Link Click, getText of a link
Radio Button Select and Toggle
Check Box Select and toggle
Image Read image
Button Click, getText on button
Selenium – GUI Controls
• Working with Firefox, IE, Chrome, HTMLUnitDriver
• GUI Controls
• Input
• Button
• Links
• Extracting all links on a webpage
• Extracting objects from a specific area of a webpage
• Finding if object is present or not
• Dropdown list
• Checkbox
• Radio Button
• Finding if object is hidden or displayed on web page
• How to take screenshot?
• Implicit and explicit wait
• PageLoadTimeout
• webDriverWaitclass
• webDriver Timeout
• ExpectedCondition interface and ExpectedConditions class
• WaitUntil Condition
• Fluent wait
• Managing Ajax based component
5/5/2021 Selenium Webdriver 2.0 68
Challenges
• Identification of web element
• Dropdown list, Button,Image,Text,Input
• Object xpath may be dynamic in nature (Every run it changes)
• Reopen website and check xpath
• Object is not visible
• Check isDisplayed property
• Object is in frame
• Check xpath window and see left hand side displays frame or right click object and
check if it is on frame
• Automation Environment unavailability
• Application stability
• Features, workflows being changed frequently leading to maintenance
issues
• Test data is changed frequently and needs regular modification and
maintenance
• Object and their properties are changes frequently
• Unreal expectation from project manager/test manager, if they expect
automation to happen at the click of a button
• Automation tool support to automate all feature of the application
• Managing test results for every build for future reference
5/5/2021 Selenium Webdriver 2.0 69
HTML Tags
• Web Element – tag, mandatory and optional HTML
tags
5/5/2021 Selenium Webdriver 2.0 70
GUI Controls
• Input
• Sendkeys
• getAttribute(“attributeName”)
• Generally input HTML tag will have VALUE aatribute –
indicate the value of the input field
• Other attributes are -- id, class, type (text), name
• Driver.findElement(By.xpath(“xpath”)).getAttribute(
“attributeName”);
• How to input value inside input field?
• sendKeys(“actual value to type”)
• clear();
5/5/2021 Selenium Webdriver 2.0 71
GUI Controls(Button)
• Button
• How to get text written on a button?
• Driver.findElement(By.xpath(“xpath”)).getAttribute(“value”);
• Driver.findElement(By.xpath(“xpath”)).getText();
• How to click on a button?
• Driver.findElement(By.xpath(“xpath”)).click();
5/5/2021 Selenium Webdriver 2.0 72
GUI Controls(Link)
• Links
• To click on a specific link : click()
• driver.findElement(By.xpath(“xpath”)).click();
• Get Text of a link : getAttribute(“value”);
• driver.findElement(By.xpath(“xpath”)).getAttribute(“value”);
• How to get a link using text written on it instead of
xpath?
• driver.findElement(By.linkText(“linktext”).click();
• driver.findElement(By.partiallinkText(“linktext”).click();
5/5/2021 Selenium Webdriver 2.0 73
GUI Controls(Link)
WebDriver driver = new FirefoxDriver();
driver.get(“http://bbc.com”);
List<WebElement> allLinks =
driver.findElements(By.tagName(“a”));
System.out.println(“Total Links : “ + allLinks.size());
// print ALL link’s text
for(int i=0;i<allLinks.size();i++)
System.out.println(allLinks.get(i).getText());
• Few links do not have text
• Few Links are hidden – allLinks.get(i).isDisplayed() // if
true, text is visible to user
5/5/2021 Selenium Webdriver 2.0 74
GUI Controls(Link)
• How to find all input fields on facebook.com
• List<WebElement> fields =
driver.findElements(By.xpath(“//input[@type=‘text’ or
@type=‘password’]”);
• System.out.println(“Total input fields are : “ +
fields.size());
• fields.get(0).sendKeys(“one”);
• fields.get(0).sendKeys(“two”);
• fields.get(0).sendKeys(“three”);
• fields.get(0).sendKeys(“four”);
• fields.get(0).sendKeys(“five”);
• fields.get(0).sendKeys(“six”);
• fields.get(0).sendKeys(“seven”);
5/5/2021 Selenium Webdriver 2.0 75
GUI Controls(Link)
• How to get links from specific area on a webpage?
• Extract all links from the red box mentioned in
below image.
5/5/2021 Selenium Webdriver 2.0 76
GUI Controls(Link)
• Procedure to get all links and click each click from red box
• Get xpath of red box
• Find all links using tagName locator for the identified xpath
• Print links
• Click on link (open a new link page) and move control back to original page
• And loop for all links
driver.get(“http://bbc.com”);
WebElement box = driver.findElement(By.xpath(“xpath of a box”));
List<WebElement> links = driver.findElements(By.tagName(“a”));
System.out.prinln(“Total Links : “ + links.size());
for (int i=0;i<links.size();i++) {
System.out.pringln(links.get(i).getText());
links.get(i).click();
System.out.prinln(driver.getTitle());
driver.get(http://bbc.com”);
box = driver.findElement(By.xpath(“xpath of a box”));
links = driver.findElements(By.tagName(“a”));
System.out.ptintln(“New Link ……………”);
}
5/5/2021 Selenium Webdriver 2.0 77
GUI Controls(Link)
• Another way to extract all links from red box
(Creating dynamic xpaths)
5/5/2021 Selenium Webdriver 2.0 78
GUI Controls(Link)
• Drawback of above method is, if links are increased
or decreased, code will not work as expected
• How to overcome this problem?
• Find out if link exist using function as below
Public static boolean isElementPresent( String ElementXpath)
{
Int count = dirver.findElements(By.xpath(ElementXpath)).size();
If (count ==0)
return false;
else
return true;
}
5/5/2021 Selenium Webdriver 2.0 79
GUI Controls(Link)
String part1=“xpath1”;
String part2=“xpath2”;
int i=1;
while(isElementPresent(part1+i+part2))
{
String text =
driver.findElement(By.xpath(part1+i+part2)).getText();
System.out.println(text);
driver.findElement(By.xpath(part1+i+part2)).click();
System.out.println(driver.getTitle());
driver.get(http://bbc.com”);
i++;
}
5/5/2021 Selenium Webdriver 2.0 80
GUI Controls(Dropdown)
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
driver.manage().window().maximize();
WebElement element = driver.findElement(By.xpath("//*[@id='Carlist']"));
Select list = new Select(element);
System.out.println("Is list multiSelect? : " + list.isMultiple());
//selects a element/item using visible text
list.selectByVisibleText("Opel");
Thread.sleep(4000L);
list.selectByIndex(3);
Thread.sleep(4000L);
list.selectByValue("Renault Car");
List<WebElement> low = list.getOptions();
System.out.println("total options : " + low.size());
for(int i=0;i<low.size();i++)
System.out.println(low.get(i).getText());
• Exercise
• Next dropdown list operation
5/5/2021 Selenium Webdriver 2.0 81
GUI Controls(Dropdown)
• How to find all elements present in dropdown list?
WebElement droplist =
driver.findelement(By.xpath(“xpath”));
List<WebElement> allOptions
=droplist.findElements(by.tagName(“option”));
System.out.println(“Total Elements present:” +
allOptions.size());
//print all elements
for(int i=0;i<allOptions.size();i++)
System.out.println(allOptions.get(i).getText()) + “ – “ +
allOptions.get(i).getAttribute(“selected”);
5/5/2021 Selenium Webdriver 2.0 82
GUI Controls(Dropdown)
• Dowpdown list using Select class
WebElement element = driver.findElement(By.xpath("//*[@id='Carlist']"));
Select list = new Select(element);
System.out.println("Is list multiSelect? : " + list.isMultiple());
//selects a element/item using visible text
list.selectByVisibleText("Opel");
Thread.sleep(4000L);
list.selectByIndex(3);
Thread.sleep(4000L);
list.selectByValue("Renault Car");
List<WebElement> low = list.getOptions();
System.out.println("total options : " + low.size());
for(int i=0;i<low.size();i++)
System.out.println(low.get(i).getText());
5/5/2021 Selenium Webdriver 2.0 83
GUI Controls(Radio Button)
• Radio Button
• Can select one radio button from a group of radio
buttons
• Radio Button either be selected or unselected.
• Html Tag - input
• Has name – group name
• Value – display text
• Type – radio
5/5/2021 Selenium Webdriver 2.0 84
GUI Controls(Radio Button)
• www.echoecho.com/htmlforms10.htm
5/5/2021 Selenium Webdriver 2.0 85
GUI Controls(Radio Button)
• driver.get(http://www.echoecho.com/htmlforms10.htm”);
• List<WebElement>
radios=driver.findElements(By.xpath(“//input[@name=‘grou
p1’]”));
• System.out.println(“Total Radio Buttons : “ + radios.size());
• System.out.println(radios.get(0).getAttribute(“checked”));
• System.out.println(radios.get(1).getAttribute(“checked”));
• System.out.println(radios.get(2).getAttribute(“checked”));
• // click on 0th radio button milk
• radios.get(0).click();
• System.out.println(radios.get(0).getAttribute(“checked”));
• System.out.println(radios.get(1).getAttribute(“checked”));
• System.out.println(radios.get(2).getAttribute(“checked”));
5/5/2021 Selenium Webdriver 2.0 86
Exercise
• Exercise
• Link
• Get text and click on “Can’t Access to you account”
on Yahoomail.com
• Radio Button
• After clicking on “Can’t Access to you account” link, get
radio buttons from next page
5/5/2021 Selenium Webdriver 2.0 87
End of Day - 1
5/5/2021 Selenium Webdriver 2.0 88
Junit framework
• What is Junit?
• Configuring Junit in Selenium
• Junit Annotations
• Running Test in Junit
• Skipping a test
• Parameterizing Tests
• Assertion
• Reporting an Error
• Batch Runner
• What is ANT – Build and Compile tool
• Downloading and configuring ANT
• Build.xml
• HTML report using ANT
• Building a BAT file to run tests using ANT
5/5/2021 Selenium Webdriver 2.0 89
TestNG Framework
• What is TestNG?
• Installing TestNG
• TestNG annotations
• Running Test in TestNG
• Batch running in TestNG
• Skipping Test
• Parameterization – DataProvider
• Assertion, Reporting errors
• TestNG Reports
• Advantages over jUnit
• Grouping tests
• Priority of execution
• DataProviders for multiple tests in single file
• Single dataprovider for multiple test cases
• Listeners for logging passed, failed, skipped test case
• TestListenerAdapter
5/5/2021 Selenium Webdriver 2.0 90
Junit Framework
• Junit is a test framework for unit testing/Functional
testing
• Junit is integrated with Selenium
• Junit is a controlling entity which controls test cases
5/5/2021 Selenium Webdriver 2.0 91
Junit Framework contd…
• Configure Junit library with project
• Configure Build path
• Annotations
• @Test : Signifies this is a test case
• @Ignore : Skips the test case
• @Before: Called before EACH test case having @Test annotation
• OpenBrowser
• @After : Called after each test case having @Test annotation
• CloseBrowser
• @BeforeClass: Executed before executed a class (once for class). This method has to be static.
• Open database connection
• @AfterClass : Executed before executed a class (once for class). This method has to be static.
• Close database connection
• Physical position does not matter.
• Test Suite: is nothing but collection of test cases
• Run suite containing 2 test cases as below
• Create tests package and Mysuite.java file containing below 2 annotations to run firsttestcase and secondtestcase
• Firsttestcase.java contains
• 2 Test method with @Test annotations
• Firsttestcase.java contains
• 3 Test methods with @Test annotations1
• Mysuite.java contains
• @RunWith(Suite.class)
• @SuiteClasses({firsttestcase.class,secondtestcase.class}) // test cases from firstclass and then test cases
from secondclass will be executed.
• And run Mysuite.java as Junit test case
5/5/2021 Selenium Webdriver 2.0 92
Junit Framework contd…
• How to decide order of execution?
• @FixMethodOrder(MethodSorters.NAME_ASCEN
DING)
• Have test case name as aa_, ab_, ac_
• Bad practice – Test cases has to be independent of
each other.
5/5/2021 Selenium Webdriver 2.0 93
Junit Framework contd…
• Can have as many Test methods as you can.
• Run Junit test script as Junit test and not Java application
• Create build.xml (copy)
• Create report folder under project folder and specify in
test.reportsDir
• HTML based reports
• Need to run Junit tests with ANT (Build and compile tool)
5/5/2021 Selenium Webdriver 2.0 94
Junit Framework contd…
• To skip all @Test inside a particular class, use
• Assume.assumeTrue(false) inside @BeforeClass annotation
OR
• Remove class name from @SuiteClasses annotation from
Mysuite.java
• Assertions
• To verify a condition and report result into Junit framework
• Assert.assertTrue(expectedResult,actualResult);
• Drawback: Once Assertion is failed, test script execution halts.
• To avoid, use try-catch block.
• Assert.AssertTrue(“Error Message”,4>3): If condition fails, error
message is executed.
• But Junit output assume that test cases is passed
• @Rule
• Public ErrorCollector errcol = new ErrorCollector();
• In catch block write errcol.addError(t);
• Try {Assert.AssertTrue(“Error Message”,4>3}catch(Throwable
t){errcol.addError(t); }
5/5/2021 Selenium Webdriver 2.0 95
Junit Framework contd…
• Parametrization
// first step – define annotation
@RunWith(Parameterized.class)
public class ParameterTestCase(){
public String username;
public String password;
public int pincode;
// second step – create constructor
public ParametertestCase(String username, String password, int pincode)
{ this.username=username;
this.password=password;
this.pincode=pincode; }
//third step
@Parameters
public static void Collection<Object>[]> getData() {
// row 1
Object[][] data = new Object[2][3]; // will executed for 2 rows
Data[0][0]=“user1”; // first iteration uesrname
Data[0][1]=“pwd1”; // first iteration password
Data[0][2]=“234123”; // first iteration pincode
//row 2
Data[0][0]=“user1”; // second iteration username
Data[0][1]=“pwd1”; // second iteration password
Data[0][2]=“234123”; // second iteration pincode
Return Arrays.asList(data); // returns object array as ArrayList }
5/5/2021 Selenium Webdriver 2.0 96
Junit Framework contd…
• Collection is a interface
• Collection a= new ArrayList();
• a.add(“Pune”);
• a.add(“Mumbai”);
• a.add(“Delhi”);
• Arrays.asList(data) : Converts Object array into arraylist
5/5/2021 Selenium Webdriver 2.0 97
Junit Framework contd…
@Test
public void testRegister()
{
System.out.println(“Registering User : “ + username + “ – “ + password
+ “ -- “ + pincode);
}
5/5/2021 Selenium Webdriver 2.0 98
ANT – Build & Compile Tool
• Ant is used to prepare HTML reports for test cases
executed
• ANT is available on Windows and Unix/Linux
• ANT is a Build, Compile and Deploy tool
• Download ANT
• http://ant.apache.org/bindownload.cgi
• Unzip the extracted file
• Copy extracted path and set environment variables
• ANT_HOME=copied path
• PATH=append ; and paste pathbin
• Go to command prompt and issue command
• Ant and press ENTER
• If no error appears ANT is successfully installed.
• Build.xml is a heart of ANT
5/5/2021 Selenium Webdriver 2.0 99
ANT – Build & Compile Tool Contd…
• Create build.xml under project folder as below
ws.home: project folder ${basedir}
Ws.jars: where all jar files are present – Selenium, poi, log4j etc.
D:jars
Test.dest: project class file stored here after compilation of project
${ws.home}/build
Test.src: ${ws.home}/src Where all .JAVA files are present
Test.reprotdir:C:rep Create this subfolder before running ANT. All
reports will be stored here.
5/5/2021 Selenium Webdriver 2.0 100
ANT – Build & Compile Tool Contd…
• Targets
Clean: Deletes target folder
Compile : deletes target folder, create again, and compile java files,
creates .class files under build folder as mentioned in build.xml
Run: Compile java files and run
add <include name=packagename/testcasename1.class/>
<include name=packagename/testcasename2.class/>
<include name=packagename/testcasename3.class/>
• Go to Command prompt and go to project folder
> ant clean
> ant compile : creates build folder and creates class files for all
java files
 ant run
 Go to c:rep which was given in build.xml for test.reportsDir
and click on index.htmls to open HTML reports
5/5/2021 Selenium Webdriver 2.0 101
ANT – Build & Compile Tool & Batch File Creation Contd…
• To run all class file created by ANT compile target use below
statement in build.xml
• <include name=**/*.class/> instead of mentioning class file
names.
• One can run Runner class MyTestSuiteRunner.class using
• <include name=packagename/MyTestSuiteRunner.class/> Will
execute all test cases (test suite) mentioned in
MyTestSuiteRunner.class
• How to Create batch file?
• Create a blank notepad file and type
cd
Cd <project path>
ant clean compile run
And save this file as “filename.bat”
• Double click this .bat file to execute all test cases. That’s all !!!!
5/5/2021 Selenium Webdriver 2.0 102
ANT – Build & Compile Tool & XSLTreprots
• How to create XSLReports
• Create a folder under src/xslt
• Copy this file into it
• Download these 2 Saxon8.7.jar and saxonLiaison.jar
files. - https://github.com/prashanth-sams/testng-
xslt-1.1.2/tree/master/lib
• Run
ant makexsltreports
• Open
<projectpath>XSLT_Reportsoutputindex.html to
see xsltreports
5/5/2021 Selenium Webdriver 2.0 103
TestNG Framework
• TestNG is most famous test framework now a days
• Many features over Junit Java framework
• Parallel test execution, GRID integration, Flashy xml reports with graph
5/5/2021 Selenium Webdriver 2.0 104
TestNG Framework Contd…
• Google “Install TestNG” click on first link (Current
release)
• Eclipse should be above 3.4
• Copy link next to 3.4 or above in Install Software in
Eclipse
• Go on clicking and finish the installation.
• Verify if TestNG is installed as a plugin
• Windows->View->Other->Java->TestNG
5/5/2021 Selenium Webdriver 2.0 105
TestNG Framework Contd…
• Configure project with TestNG library and selenium jar files.
• Test NG Annotations
• Has predefined order of execution. Method can have any name for all annotations.
• @Test: This is a test case
• @BeforeMethod: Executes with every @test annotation
• Used to open browser
• @BeforeTest: Executes first before executing any of the test. Executed only once in the execution.
• Used to connect to database.
• @AfterMethod: Executes with every @test annotation after @Test annotation is execute.
• Used to close browser
• @AfterTest: Executes first after executing any of the test. Executed only once in the execution.
• Used to shutdown/close to database.
• @BeforeSuite: Executed before executing a test suite (Test suite is a collection of test cases) This annotation can
be present in one of the test script (across multiple java files) if there are multiple suites.
• Initialize or create webdriver interface.
• @AfterSuite: This annotation can be present in one of the test script if there are multiple suites.
• Any no of @Test annotations can be created
• When run, any test case can run first, there is not predefined order for running test cases. Priority defines
execution order.
• Test-output folder is created
• Index.html is created where HTML report is created automatically.
• Run as a TestNG test
• You can see HTML report in test-output folder.
• Observe
5/5/2021 Selenium Webdriver 2.0 106
TestNG Framework Contd…
• To run multiple java files using TestNG, testng.xml is
required and should be under project folder.
• 2 Class files under testPkg package
• Single test can be skipped by mentioning skip new
… inside test annotation.
• Check report to see passed, failed and skipped
result
5/5/2021 Selenium Webdriver 2.0 107
TestNG Framework Contd…
• Skipping a test case
• In @BeforeTest annotation use
• throw new SkipException(“Skipping a test case”);
• Parameterization
• Running a single test with multiple set of data
• Logging in to Gmail.com
• DataSets are
• Valid user, valid password
• Valid username, invalid password
• Invalid username, valid password
• Invalid username, invalid password
5/5/2021 Selenium Webdriver 2.0 108
TestNG Framework Contd…
• @DataProvider
Public Object[][] getData()
{
Object[][] data = new Object[4][2]; // test will be repeated for 4 times, 2 are
the no of columns
//row1
Data[0][0]=“valid user”;
Data[0][1]=“valid password”;
//row2
Data[1][0]=“valid user”;
Data[01[1]=“invalid password”;
// row3
Data[2][0]=“invalid user”;
Data[2][1]=“valid password”;
//row4
Data[3][0]=“invalid user”;
Data[3][1]=“invalid password”;
Return data;
}
5/5/2021 Selenium Webdriver 2.0 109
TestNG Framework Contd…
• @Test(dataPriovider=“getData”)
• Public void Login(String username, String password)
• {
• System.out.println(username + “ – “ + password);
• }
• Run above test using testng.xml
5/5/2021 Selenium Webdriver 2.0 110
TestNG Framework Contd…
• Assertions
• To check if a specific condition is satisfied or not
• Example: Link is present, specific text is present
• Assert.assertEquals(expectedResult,ActualResult);
• Assert.assertEquals(x,y);
• If value of x <> value of y then fail the test case else pass.
• Check the HTML report for result
• Assert.assertTrue(message,condition);
• Assert.assertTrue(“Error message”,6>1);
• If condition evaluates to true, test will pass else fail.
• Assert.assertFalse(message,condition);
• If condition evaluates to false, test will pass else fail.
5/5/2021 Selenium Webdriver 2.0 111
TestNG Framework Contd…
• Statements after assertion statement is not
executed when assertion is failed and control goes
to next test case.
• IF you want to continue even when assertion
fails(for minor error), use try catch block. (with
throwable – Error and Exception). When assertion
fails, control moes to catch block and TestNG
reports test case as passed and not failed.
5/5/2021 Selenium Webdriver 2.0 112
TestNG Framework Contd…
• Build.xml changes
• Target “run” should have below statement
• <xmlsfileset dir=“${ws.home}” includes=“testng.xml”
• To run reports use command
• ant makexlstreports
• Where makexlstreports is a target like clean, compile, run
• Below jar files are required and configure with project. (Download from
<http://www.java2s.com/Code/Jar/s/Downloadsaxon87jar.htm>)
• Create xslt package under project folder, create testng-results.xsl file.
• Issue command ant clean compile run makexsltreports
• Compile project if there are changes done in project code
• Refresh project folder in Eclipse
• XLST_Reports folder is created and xlst reports are generated
• Test-output are primitive HTML reports
5/5/2021 Selenium Webdriver 2.0 113
TestNG Framework Contd…
• Order of test case execution will not be dependent on physical
position. But it depends on priority.
• Order of execution : testChangePwd,testLogout,testLogin
• If testLogin test case fails other 2 test cases will be skipped.
• @Test(priority=3,dependsOnMethods={“testLogin”})
• Public void testLogout(){ System.out.println(LogoutTest”);
• @Test(priority=2,dependsOnMethods={“testLogin”})
• Public void testChangePwd(){ System.out.println(Password
Change Test”);
• @Test(priority=1)
• Public void testLogin(){ System.out.println(LoginTest”);
• // Assert.assertEquals(“A”,”B”); fails test case
5/5/2021 Selenium Webdriver 2.0 114
TestNG Framework Contd…
• Separate dataProviders with different names in single java file. Many test cases
with many dataproviders but in single java file.
• Data_Provider.java
Public class Data_provider // dataprovider 1
{ @DataProvider(name=“regTestDataProvider”)
Public static Object[][] getData()
{ Object data[][]=new Object[2][3];
Data[0][0]=“U1”;
Data[0][0]=“P1”;
Data[0][0]=“xyz@gmail.com”;
Data[1][0]=“U2”;
Data[1][1]=“P2”;
Data[1][2]=abc@gmail.com”;
Return data;} }
Public class Data_provider // dataprovider 2
{@DataProvider(name=“loginTestDataProvider”)
Public static ?Object[][] getLoginData()
{Object data[][]=new Object[2][3];
Data[0][0]=“U1”;
Data[0][0]=“P1”;
Data[1][0]=“U2”;
Data[1][1]=“P2”;
Return data;}}
5/5/2021 Selenium Webdriver 2.0 115
TestNG Framework Contd…
• Associate dataprovider with test case
• Sample.java
• Public class SampleTest{
• @Test(priority=1,dataProviderClass=Data_Provider.class,data
Provider=“loginTestDatAProvider”)
• Public void testLogin(String username, String password){
• System.out.println(“Login Test ” + username + “ – “ +
password); }
• @Test(priority=2,dataProviderClass=Data_Provider.class,data
Provider=“regTestDataProvider”)
• Public void testReg(String username, String password, String
email){
• System.out.println(“Login Test ” + username + “ – “ +
password + “ – “ + email); }
5/5/2021 Selenium Webdriver 2.0 116
TestNG Framework - ANT Contd…
• XSLT stands for XML (Extensible Markup Language) Stylesheet
Language for Transformations.
XSLT gives interactive(user friendly) reports with "Pie Chart"; but
only on TestNG framework.
• Create folder srcxslt
• Create testng-results.xls file (copy)
• Create build.xml and update it
• Go to project folder
• ant clean compile run
• An makexsltreports
• Create a BATCH file
• cd
• F:rishikeshSeedInfoTechTestNG
• Ant clean compile run makexsltreports
5/5/2021 Selenium Webdriver 2.0 117
Reading a properties file
• .properties
• Name=“Tom”
• Age=23
• City=Pune
• #Hobbies=Cricket,Football
• Browser=Firefox
• testsiteURL=http://gmail.com
• Comments are indicated by#
• Properties prop = new Properties();
• FileInputStream fs = new
FileInputStream(“D:temptemp.properties”);
• Prop.load(fs);
• System.out.println(prop.getProperty(“name”));
• System.getProperty(“user.dir”) – returns project folder
5/5/2021 Selenium Webdriver 2.0 118
POI Library – Accessing Excel Files
• POI Library by Apache
• Used to access Excel file
• Very rich library containing all methods to
read/write/delete/update workbooks, sheets, cells
• Download and configure below 5 Jar files to work with
Excelfiles
5/5/2021 Selenium Webdriver 2.0 119
POI Library – Accessing Excel Files contd...
• Create Excel file data.xls on D:temp in sheet ‘details’
Name Age City
Ankit 21 Pune
Amruta 20 Mumbai
Shailesh 23 Nagpur
Ramita 21 Delhi
Xls_Reader xls = new Xls_Reader(“D:tempdata.xls”);
int totRow = Xls.getRowCount(“details”);
int totCol = Xls.getColCount(“details”);
String Data = xls.getCellData(“details”,”Name”,3);
xls.SetCellData(“details”,”Name”,6,”Asin”);
5/5/2021 Selenium Webdriver 2.0 120
Logging Data
• Allows to write logs/errors/debug messages into log file
• Create or copy log4j.proeprties into project folder (src)
• Download log4j API and configure in project
• Log4j API reads log4j.proeprties
• import org.apache.log4j.Logger;
• Create Logger object ponting to devpinoyLogger
• Log4j.properties contents.
•
5/5/2021 Selenium Webdriver 2.0 121
Logging Data contd…
• Logger ApplLogs = Logger.getLogger(“devpinoyLogger”);
• ApplLogs.debug(“Logging started….”);
• ApplLogs.debug(“Logging in progress….”);
• ApplLogs.debug(“Logging ending….”);
5/5/2021 Selenium Webdriver 2.0 122
Working with Different Browsers
• How to use Firefox browser?
• WebDriverdriver = new FirefoxDriver();
• How to use Chrome browser?
• System.setProperty(“webdriver.chrome.driver”,”path of
chromedriver”);
• WebDriverdriver = new ChromeDriver();
• How to use IE browser?
• System.setProperty(“webdriver.ie.driver”,”path of IE
driver”);
• WebDriverdriver = new InternetExplorerDriver();
5/5/2021 Selenium Webdriver 2.0 123
Screenshot
• How to take screenshot when error occurs?
• // get screenshot in binary form
• File scrFile=((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
• // convert into jpg format to specified destination
• FileUtils.copyFile(scrFile,new
File(“F:RishikeshSeedInfoTechScreenshotsgmail.j
pg”));
• FileName – Generate unique file name using date and
time
5/5/2021 Selenium Webdriver 2.0 124
Screenshot
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int sec = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);
int hour = cal.get(Calendar.HOUR);
int date = cal.get(Calendar.DATE);
int day = cal.get(Calendar.HOUR_OF_DAY);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date1 = new Date(); //get current date time with Date()
String date2= dateFormat.format(date1);
System.out.println(date2); // Print the Date
System.out.println("month : " + month);
System.out.println("year : " + year);
System.out.println("sec : " + sec);
System.out.println("minute : " + minute);
System.out.println("hour : " + hour);
System.out.println("date : " + date);
System.out.println("day : " + day);
fileName = year+"_"+date+"_"+(month+1)+"_"+day+"_"+minute+"_"+sec+".jpg";
// convert into jpg format to specified destination
FileUtils.copyFile(scrFile,new File("F:RishikeshSeeedInfoTechScreenShotsgmail" + fileName +".jpg"));
5/5/2021 Selenium Webdriver 2.0 125
Exercises
• Go to Dice.com search selenium jobs
• Click on each page link 1,2,3,4,5
• Go to google.com
• Search for mobile phone
• Print all links on the first page
5/5/2021 Selenium Webdriver 2.0 126
Waits
• Implicit and Explicit wait
• PageLoadTimeout
• WebDriverWait Class
• Expectedcondition class
• WaitUntil Condition
• Fluent Wait
• Managing Ajax based components
• Yahoo.com
• Google.com
• Window Handles
5/5/2021 Selenium Webdriver 2.0 127
Implicit Wait
• Implicit wait – Global timeout
• driver.manage().timeouts().implicitlywait(10,TimeU
nits.SECONDS);
• findElements waits for 10 Second maximum before
it finds an element.
• This setting is applicable to complete test script
5/5/2021 Selenium Webdriver 2.0 128
Explicit Wait
• Is not a global wait
• Its specific to an element
• Waits for specific condition is true/met
• Two types of classes used (implements wait
interface)
1. WebDriverWait
2. FluentWait
5/5/2021 Selenium Webdriver 2.0 129
Explicit Wait
• Hdfc.com
• webDriverWait wait = new
webDriverWait(driver,20); // Selenium polls with every
microsecond if the element is found
• wait.until(ExpectedConditions.visibilityOfElementLo
cated(By.xpath(“xpath”))
• wait.until(ExpectedConditions.invisibilityOfElement
Located(By.xpath(“xpath”))
5/5/2021 Selenium Webdriver 2.0 130
FluentWait
• Wait for a specific element is found
• FluentWait<WebDriver> fwait = new
FluentWait<WebDriver>(driver)
• .withTimeout(30,TimeUnits.SECONDS)
• .pollingEvery(5,TimeOuts.SECONDS)
• .ignoring(NoSuchElementException.class);
• Explanation
• Waits for 30 seconds
• Polls every 5 seconds
• Ignores NoSuchElementException exception
• Example
• fwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpat
h(“xpath”)));
• s
5/5/2021 Selenium Webdriver 2.0 131
Wait- PageLoadTimeout
• driver.manage().timeouts().pageLoadtimeout(30,Ti
meUnits.SECONDS);
• If new page is not loaded in specified SECONDS,
selenium will throw exception.
5/5/2021 Selenium Webdriver 2.0 132
Alerts
Alert al = driver.switchTo.alert();
System.out.println(al.getText());
Al.accept(); // or Al.dismiss()
// switch to main window back
driver.switchTo().defaultContent();
5/5/2021 Selenium Webdriver 2.0 133
Window Handling
• Each window has unique window id
WebDriver driver = new FirefoxDriver();
Set<String> windIds = driver.getWindowHandles(); // ordered set
System.out.println(“Total windows opened : “ + windIds.size()); // 1 window
Iterator<String> it = windIds.iterator();
System.out.println(it.next());
driver.get(http://in.rediff.com”); // opens popups along with in.rediff.com webpage
windIds = driver.getWindowHandles();
System.out.println(“total windows opened : “ + windIds.size()); // 2 windows
it = windIds.iterator(); // again initialize iterator
String mainWindow = it.next();
String popupWindow = it.next();
System.out.println(mainWindow); // unique window id
System.out.println(popupWindow );
Exercise: http://timesofindia.indiatimes.com/ Click on Facebook icon
5/5/2021 Selenium Webdriver 2.0 134
Window Handling – Another example
WebDriver dr = new FirefoxDriver();
dr.get("https://www.salesforce.com/in/form/semfy16/crm-
demo_b.jsp?d=70130000000t1oD&DCMP=KNC-
Google&mkwid=6YuZhCqn&pcrid=70285087026&type=Exact&pdv=c");
dr.findElement(By.xpath("//*[@id='form-container']/div[3]/div/a[2]")).click();
Set<String> windIds = dr.getWindowHandles();
System.out.println("total windows opened : " + windIds.size());
Iterator<String> it = windIds.iterator();
String mainWindow = it.next();
String childWindow = it.next();
dr.switchTo().window(childWindow);
Thread.sleep(5000L);
System.out.println(dr.findElement(By.xpath("//*[@id='content']/div[1]/div/h1")).getText());
Thread.sleep(3000L);
dr.switchTo().window(mainWindow);
System.out.println(dr.findElement(By.xpath("//*[@id='layout']/div[1]/div[1]/div/div/div/div[2]/div/div
/h2")).getText());
Exercise: http://timesofindia.indiatimes.com/ Click on Facebook icon
5/5/2021 Selenium Webdriver 2.0 135
Frame Handling
• Elements on frame are not accessible unless the focus is moved to frame
WebDriver dr = new FirefoxDriver();
dr.get("http://www.firstcry.com/");
dr.findElement(By.xpath("html/body/div[5]/div[1]/div/div[2]/span[5]")).click();
int sz = dr.findElements(By.tagName("iframe")).size();
System.out.println("Total frames on page are " + sz);
int cnt = 0;
int i=0;
int flag = 0;
for(i=0;i<sz;i++)
{ dr.switchTo().frame(i);
cnt = dr.findElements(By.xpath("//*[@id='Email']")).size();
if (cnt !=0)
{ flag = 1;
dr.findElement(By.xpath("//*[@id='Email']")).sendKeys("AAAAA");
break; }
dr.switchTo().defaultContent(); }
if (flag == 1)
{System.out.println("Element contains in frame : " + i);}
else
System.out.println("Element does not contain in any frame"); }
5/5/2021 Selenium Webdriver 2.0 136
Frame Handling
Another Example
WebDriver dr = new FirefoxDriver();
dr.get("http://www.w3schools.com/html/tryit.asp?filename
=tryhtml_iframe_height_width");
int totFrames =
dr.findElements(By.tagName("iframe")).size();
System.out.println("Total frames on main page : " +
totFrames );
dr.switchTo().frame(0);
dr.switchTo().frame(0);
System.out.println(dr.findElement(By.xpath("html/body/h1
")).getText());
5/5/2021 Selenium Webdriver 2.0 137
Browser - Forward-Backward
WebDriver dr = new FirefoxDriver();
dr.navigate().to("http://hdfc.com/");
dr.manage().timeouts().implicitlyWait(5,
TimeUnit.SECONDS);
dr.manage().window().maximize();
dr.findElement(By.xpath("//*[@id='node-
18']/div/div/div/div/div[2]/nav/ul/li[2]/a")).click();
Thread.sleep(5000L);
dr.navigate().back();
Thread.sleep(5000L);
dr.navigate().forward();
5/5/2021 Selenium Webdriver 2.0 138
Actions class – Mouse Movement
• Mouse deals with element which is not visible ut can be visible by moving mouse over it.
• If element is not visible, selenium will not click on it
• Write a program to click on GlofMenu->Woods->Driver – Should not work
• Make element visible in order to click
• Example
• Clicking on GlofClubs->Woods->Driver
WebDriver dr = new FirefoxDriver();
dr.get("http://www.americangolf.co.uk/");
Actions act = new Actions(dr);
WebElement mainMenu = dr.findElement(By.xpath("//*[@id='navigation']/nav/ul/li[1]/a"));
Thread.sleep(3000L);
act.moveToElement(mainMenu).build().perform();
Thread.sleep(2000L);
System.out.println("Moved to Gold Clubs menu");
WebElement driverMenu =
dr.findElement(By.xpath("//*[@id='CLUBS_1']/div[1]/ul[2]/li/ul/li[2]/ul/li[1]/a"));
Thread.sleep(3000L);
act.click(driverMenu).build().perform();
System.out.println("Moved to Woods->Driver menu") Exercise
• Print all links within Golf club main menu
• Code in Notes section
• Move price slider using Mouse class.
• Code in Notes section
5/5/2021 Selenium Webdriver 2.0 139
Miscellaneous
• How to generate random number?
Random r = new Random();
Int x = r.nextInt(100); // print no from 0 to 99
System.out.println(x);
• Drag & drop – Price Slider
Driver.get(http://www.americangolf.co.uk/golf-
clubs/drivers?pmax=230&prefn1=brand&pmin=175&prefv1=CobraGolf);
Actions act = new Actions(driver);
WebElement point = driver.findElement(By.xapth(“xpath”));
act.dragAndDropBy(point,-100,0).build.perform();
• System.getProperty(“user.dir”) – Returns current project folder
• driver.getTitle() – Returns current window title
• driver.quit – closes all related windows
• driver.close – closes current window
• dr.manage().window().maximize() – maximizes current window
5/5/2021 Selenium Webdriver 2.0 140
WebTable
• Table on webpage is called web table.
• Web table has rows and columns
• HTML table structure
• HTML tag – table
• tr - table row
• td – table data/cell
• http://www.w3schools.com/html/html_tables.asp
5/5/2021 Selenium Webdriver 2.0 141
WebTable
• Xpaths to identify complete row, col and cell value/s
• 4th row and 2nd column value
• //table[@class=‘reference’]/tbody/tr[4]/td[2]
• Complete First row
• //table[@class=‘reference’]/tbody/tr[1]
• Complete First row
• //table[@class=‘reference’]/tbody/tr[1]/td
• Column 2
• //table[@class=‘reference’]/tbody/tr/td[2]
• All cells of a table
• //table[@class=‘reference’]/tbody/tr/td
5/5/2021 Selenium Webdriver 2.0 142
WebTable
• Goto Rediff.com->Money
• Print web table row by row
driver.get(“”);
List<WebElement> rows =
driver.findElements(By.xpath(“table[@class=‘reference’]/tbody/tr”));
System.out.println(“total rows are : “ + rows.size());
for (int i=0;i<rows.size();i++)
Systen.out.println(rows.get(i).getText());
• Print company name from first column of all rows
/table[@class=‘reference’]/tbody/tr/td[1]
5/5/2021 Selenium Webdriver 2.0 143
WebTable
• Goto Rediff.com->Money
• Print web table row by row
driver.get(“”);
List<WebElement> rows =
driver.findElements(By.xpath(“table[@class=‘reference’]/tbody/tr”));
System.out.println(“total rows are : “ + rows.size());
for (int i=0;i<rows.size();i++)
Systen.out.println(rows.get(i).getText());
• Print company name from first column of all rows
/table[@class=‘reference’]/tbody/tr/td[1]
5/5/2021 Selenium Webdriver 2.0 144
WebTable
• Print price of a specific company
String companyName=“Bata India”;
List<WebElement> companyNames=
driver.findElements(By.xpath(“/table[@class=‘reference’]/tbo
dy/tr/tr[1] ”));
List<WebElement> currentPrices =
driver.findElements(By.xpath(“/table[@class=‘reference’]/tbo
dy/tr/tr[4]”));
For(int i=0;i<companyNames.size();i++)
{
If (companyNames.get(i).getText().equals(companyName))
Systen.out.println(companyNames.get(i).getText() + “ – “ +
currentPrices.get(i).getText() );
}
5/5/2021 Selenium Webdriver 2.0 145
WebTable
• Print web table cell by cell
List<WebElement> table=
driver.findElements(By.xpath(“/table[@class=‘reference’]/tbo
dy/tr/td”));
for(int i=0;i<table.size();i++)
System.out.println(table.get(i).getText());
5/5/2021 Selenium Webdriver 2.0 146
End of Day - 2
5/5/2021 Selenium Webdriver 2.0 147
Framework Structure
5/5/2021 Selenium Webdriver 2.0 148
Framework
What is Framework?
• A method or process with which one can
• Maintain script
• Log messages/errors
• Create reports
• Read data from various inputs like CVS file, Excel, database
• Handle errors
• Configure various environmental variables
• Create faster test scripts
• One time efforts
• Junit and TestNG - Java Framework
• DataDriven framework is a concept
• Core framework – generic framework for any website
Data Driven framework
• Allows to drive test script with data from external input like database, CVS,
Excel files.
• Test scripts are not required to modify but only configuration file
5/5/2021 Selenium Webdriver 2.0 149
Framework
• Explain framework on board and then using test script
• Each sheet contain data for single test case with sheet name = test case name
• All data is stored in a single sheet
• One sheet for test suite with suitename, runmode column
• One sheet for TCID, comment, Runmode
• One sheet for TCID, data1, data2, data3, runmode
• Create Below Packages
• Core
• Main driver class to initialize Config, OR properties, define public variables – log, webdriver, database initialize
• Load Excel file for data
• Logs
• Log4j properties helps to log errors/messages
• Properties
• Config.proerpties
• Browser, TestSiteURL, ScreenshotPath
• Objects.properties
• xpaths
• Testdata.xls
• Sheets – TestSuite, LoginTest, registerUserTest
• TestSuites – TCID, Desc, RunMode
• LoginTest – username, password, positiveTest
• RegisterUserTest - name, day, month, year, registerusername, password, repassword, email
• Tests
• LoginTest
• RegisterUserTest
• Utility
• Common utility methods/functions – isElementPResent, click, type
• Common Application methods/functions – login, logout, IsTestSuiteExecutable, isTestCaseExecuteble, isTestDataSetExecutable
• XlsReader
• Excel file for input data
• Implementation using Junit framework
• Create below folders
• Screenshot
• Build.xml – To run project using ANT build and compile tool
• Application.log
5/5/2021 Selenium Webdriver 2.0 150
Framework
• LoginTest.java
• Write constructor
• Use Parameterization using Junit
• RegisterUserTest
• Write constructor
• Use Parameterization using Junit
• Show Run of framework (GUI) and show report
5/5/2021 Selenium Webdriver 2.0 151
Framework
• Step by Step procedure to create data driven framework
• Using TestNG and WebDriver
• Create a project – WebDriverTestNGDataDrivenFramework
• Create package
• dd_core – initialize variables, database connection, reading
properties file
• dd_logs – to maintain application logs – user defined
• dd_properties – To read properties config and OR properties
• dd_tests – Write and maintain all test cases
• Rough – for rough work
• dd_util – common application and common application
functions
• Write a code to capture a screenshot
• Create config.properties file under dd_properties package
• Create object.properties file under dd_properties package
for maintaining xpaths/locators for link, input, buttons etc.
5/5/2021 Selenium Webdriver 2.0 152
Framework
• config.properties
• testsite=http:/twitter.com
• browser=firefox
• Copy below 3 files into dd_util
• DbManager.java, MonitoringMail .javaand TectConfig.java
• Create application.log and selenium.log under dd_logs package
• Configure Jar files for
• Selenium
• Poi jar files
• TestNG Library
• Log4j jar file
• Mail.jar
• Create test Core class under dd_core package
• Initializing properties, Loading excel files, Creating DB connection, generating logs, init
webDriver
• Copy IEdriver and chromedriver into util package
• Create testdata.xlsx under dd_properties
• Sheets – TestSuite, LoginTest, registerUserTest
• TestSuites – TCID, Desc, RunMode
• LoginTest – username, password, positiveTest
• RegisterUserTest - name, day, month, year, registerusername, password, repassword,
email
• Enter data into all sheets as mentioned in Notes
5/5/2021 Selenium Webdriver 2.0 153
Framework
• Copy xls_reader.java under dd_util package
• testCore class
public static Properties config = new Properties();
public static Properties object = new Properties();
public static Xls_Reader excel = null;
public static WebDriver driver = null;
@BeforeSuite
public static void init()
{
If (driver == null) {
//loading config , object properties and excel file
FileInputStream fis = new FileInputStream(System.getPRoperty(“user.dir” + “srcdd_propertiesconfig.properties”);
config.load(fis);
FileInputStream fis = new FileInputStream(System.getPRoperty(“user.dir” + “srcdd_propertiesOR.properties”);
object.load(fis);
excel = new Xls_Reader(System.getProperty(“user.dir”) + “srcdd_propertiestestdata.xlsx” );
// decide webdriver to open browser
If (config.getProperty(“browser”) .equals== “firefox”)
driver = new FirefoxDriver();
Else if (config.getProperty(“browser”) .equals== “chrome”)
{ System.getPRoperty(“webdriver.chrome.driver”,”chromedriver.exe”); //copy driver to project folder
driver = new ChromeDriver(); }
Else if (config.getProperty(“browser”) .equals== “ie”)
{ System.getPRoperty(“webdriver.ie.driver”,”ieDriverServer.exe”); //copy driver to project folder
driver = new InternetExplorerDriver(); }
}}
driver.manage().timeouts.implicitlyWait(20,TimeUnit.SECONDS);
driver.get(config.navigate(“testsite”));
}
5/5/2021 Selenium Webdriver 2.0 154
Framework
• @AfterSuite
• public static void quitDriver()
• {driver.quit();
• monitoringMail mail = new monitoringMail();
• mail.sendMail(TestConfig.server,TestConfig.from, TestConfig.to, TestConfig.subject, TestConfig.messageBody,
TestConfig.attachmentPath, TestConfig.attachmentName);
• }
• Object.properties
• #LoginTest
• username=//*[@id='signin-email']
• password=//*[@id='signin-password']
• signin=//*[@id='front-container']/div[2]/div[2]/form/table/tbody/tr/td[2]/buttondd_tests
• Create LoginTest.java in dd_tests
• @Test
• public class LoginTest extends testCore{ // to use webdriver variable, properties files
• @BeforeTest
• public void isSkip(){
• If (!TestUtil.isExecutable(“LoginTest”))
• Throw new skipException(“Skipping test case as the run mode is set to N”);
• }
• public void doLogin()
• {
• driver.findElement(By.xpath(object.getProperty(“username”))).sendKeys(“AAAAA”);
• driver.findElement(By.xpath(object.getProperty(“password”))).sendKeys(“BBBBB”);
• driver.findElement(By.xpath(object.getProperty(“signin”))).click();
• }}
5/5/2021 Selenium Webdriver 2.0 155
Framework
Update testdata.xlsx for tCid and Runmode columns with
Tcide runmode
LoginTest N
Create TestUtil file under dd_utils
public class TestUtil extends Testcore {
public static boolean isExecutable()
{
System.out.println("Tot rows : " + excel.getRowCount("test_suite"));
for(int r=2;r<=excel.getRowCount("test_suite");r++)
{
System.out.println("test : " + excel.getCellData("test_suite", "tcid", r));
if ( excel.getCellData("test_suite", "tcid", r).equals("LoginTest"))
{
System.out.println("inside tcid row...");
if (excel.getCellData("test_suite", "runmode", r) == "Y")
return true;
else
return false;
}
else
return false;
}
return true;
}
5/5/2021 Selenium Webdriver 2.0 156
Framework
• Update LoginTest for
• isSkip method – Modification is already done in LoginTest.java in prior slide.
• Run the project now.
• Pass tcid to isExecutable function and change isExecutable and replace “LoginTest” with
“tcid” parameter.
• Write one more test case called secondtest and mentioned it in testdata.xls as runmode set
to N
• Copy LoginTest method as secondtest
• Create testng.xml under project folder as below
5/5/2021 Selenium Webdriver 2.0 157
Framework
• Pass username, password to doLogin method and have
• @Test(dataProvider=“getdata”)
• In the same file write Dataprovider as below
• @DataProvider
• public Object[][] getData()
• {
• String sheetName=“LoginTest”;
• int rows = excel.getRowCount(sheetName);
• int cols = excel.getColumnCount(sheetName);
• Object data[][] = new Object[rows-1][cosl];
• for(int rowNum=2;rowNum<=rows;rowNum++)
• {for (int colNum=0;colNum<cols;colNum++)
• data[rowNum-2][colNum] = excel.getCellData(sheetName, colnum,
rowNum); }
• return data;
• }
5/5/2021 Selenium Webdriver 2.0 158
Framework
• Run the framework (Ensure LoginTest sheet has data for login –
username, password with 2 rows )
• For Every other test case whichever requires parameter, we will
have getData() method copied in the test script. To avoid the
duplicate code, write common function getData(String
sheetName) in TestUtil package
• @DataProvider
• Public object[][] getData()
• {
• Return TestUtils.getData(“LoginTest”);
• }
5/5/2021 Selenium Webdriver 2.0 159
Framework
• Write one more static method in TestUtils package
• Public static Object[][] getData(String sheetName)
• {
• int rows = excel.getRowCount(sheetName);
• int cols = excel.getColumnCount(sheetName);
• Object data[][] = new Object[rows-1][cols];
• for(int rowNum=2;rowNum<=rows;rowNum++)
• {for (int colNum=0;colNum<=cols;colNum++)
• Data[rowNum-2][col] = excel.getCellData(sheetName,
colNum, rowNum); }
• return data;
• }
5/5/2021 Selenium Webdriver 2.0 160
Framework
• Interpretation of TestNG output
• Green – pass
• Yellow – Skipped
• Red – Failed
• Application Logging
• testCore.java
• Public static Logger appl_logs =
Logger.getLogger(“devpinoylogger”);
• Import files from org.apache.log4j not from testng
• log4j.proeprties file
• Only change the log file path where log file is generated
5/5/2021 Selenium Webdriver 2.0 161
Framework
• Log4j.properties contents
• In respective places add below statements
• apps_logs.debug(“Loading config properties file”);
• apps_logs.debug(“Loading OR properties file”);
• apps_logs.debug(“Loading Excel properties file”);
5/5/2021 Selenium Webdriver 2.0 162
Screenshot
• TestUtils.java add one more method
public static void captureScreenshot(String suffix){
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH); // current month
int year = cal.get(Calendar.YEAR); // current year
int sec = cal.get(Calendar.SECOND); // current second
int min = cal.get(Calendar.MINUTE); // current minute
int date = cal.get(Calendar.DATE);
int day= cal.get(Calendar.HOUR_OF_DAY);
//create unique file name with current timestamp
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try{
String mailscreenshotpath =System.getProperty("user.dir")+"dd_logsscreenshots"+ suffix
+year+"_"+date+"_"+(month+1)+"_"+day+"_"+min+"_"+sec+".jpg";
FileUtils.copyFile(scrFile,new File(mailscreenshotpath));
} catch(IOException e){e.printStackTrace();}}
• TestUtils.captureScreenshot(); // wherever you want to capture screenshot especially when test
script is failed.
• Run the framework right clicking on testng.xml and check screenshot folder for screenshots.
5/5/2021 Selenium Webdriver 2.0 163
Framework
• Drawback of current data driven framework
• If you have 10000 test cases, creating and maintaining 10K
sheets will be difficult
• To avoid this one can have all test case data in one sheet
5/5/2021 Selenium Webdriver 2.0 164
Error Handling & Reporting Error in TestNG
• How to report errors in TestNG report?
• Change password xpath to wrong xpath and make changes as below and run testng.xml
• Put all statements in try and catch block in loginTest test script and inside catch
block
• Catch (Throwable t)
• {
• TestUtils.capturescreenshot(); // captures screenshot in case of error
• Assert.assertTrue(false, t.getMessage()); // report failure in TestNG
report/console
• }
• If there is no data for a test case, in that case TestUtils.getdata() should be
changed to accommodate below changes
• int rows = excel.getRowCount(sheetName)-1;
• If (rows <=0)
• {Object data[][] = new Object[1][0];
• Return data;}
• Whenever there is a failure in the test case – failure is reported in testNG report,
and control moves on to the next test case.
5/5/2021 Selenium Webdriver 2.0 165
Framework
• Create xls package under project folder
• Download and configure Testng-xslt-maven-plugin-test-0.0.jar and saxon jars are present.
• http://software-testing-tutorials-automation.blogspot.in/2014/07/download-required-jar-files-for.html
• Configure ANT and create build.xml (prior to src folder)
• Change 1.5 to 1.8 under compile target
• Before running using ant ensure project is run using testng.xml from Eclipse and check reports as
well
• Go to project folder (prior to src folder)
• ant clean compile run
• Ensure to have makexsltreports target in build.xml
• Copy testng.xls (module21 Hybridframework) to srcxlst folder
• Goto project folder on command prompt
• ant clean compile run makexsltreports
• Go to Eclipse and refresh folder and observe xlst_reports
• Open index.html file to see xslt reports
5/5/2021 Selenium Webdriver 2.0 166
Framework
5/5/2021 Selenium Webdriver 2.0 167
Hybrid Driven Framework
• Combination of Data and Keyword
• Requires less programming
• Big projects are using hybrid driven framework
• Process of creating hybrid driven framework
• Decide which Java framework to use – TestNG or JUnit
• Create DriverApp/keywordApp
• Define keyword – Heart of Hybrid framework
• Typing a text, entering field value, click on a link
• Create test data file
• Create keyword file
• Create report.java – will generate report for each test case
• Create email code file for sending failed test case report
• Integrate ANT
5/5/2021 Selenium Webdriver 2.0 168
Hybrid Driven Framework
5/5/2021 Selenium Webdriver 2.0 169
POM
• POM – Page Object Model
• Based on webpages
• Example there are 10 pages, will create 10 java files
• Based on encapsulation and inheritance
• When to use POM?
• When there are similar web pages
• Example facebook.com everyone has a wall but with different content
• Twitter.com
• POM can be implemented using Junit or TestNG
• School IS A institution -- inheritance
• FirefoxDriver implments WebDriver interface
• Public class School extends institution -> Schools class acquires all properties of institution.
• { Room r = null;
• Public School (Room r){this.r=r;}
• School Has A room (class rooms) – Encapsulation
• Test.java
• Public class Room{
• Public int space;
• Public void setSpace(){space=s;}
• Public void getSpace(){System.out.println(s);}
5/5/2021 Selenium Webdriver 2.0 170
POM
• Its data driven model
• Most happening framework now a days
• What is encapsulation?
• HAS a relationship
• Building HAS a BATHROOM
• What is inheritance?
• IS A relationship
• House IS A building
• DOG IS A animal
• House extends Building
• Object of House can access variables and methods from
Building class(Parent)
5/5/2021 Selenium Webdriver 2.0 171
POM - Inheritance
House IS A building
Building.java
public class Building {
public void getColor()
{
System.out.println("Color Blue...");
} }
House.java
public class House extends Building{ }
Test.java : Run this script
public class test {
public static void main(String[] args) {
House h = new House();
h.getColor();
}}
5/5/2021 Selenium Webdriver 2.0 172
POM - Encapsulation
• HAS A relationship
• House has a bathroom
• Bathroom object can be created inside House class
• Bathroom.java
public class Bathroom {
public int mirrors;
public void setMirrors(int m)
{ mirrors=m; }
public int getMirrors()
{ return mirrors; }}
• House.java
public class House extends Building{
Bathroom b = null;
public House(Bathroom b)
{ this.b = b; }}
• Test.java
public class test {
public static void main(String[] args) {
Bathroom b = new Bathroom();
b.setMirrors(3);
House h = new House(b);
System.out.println("Mirrors: " + h.b.getMirrors()); }}
5/5/2021 Selenium Webdriver 2.0 173
POM
• CAR HAS a registration no
• Car.java
public class Car {
String model;
RegistrationNo reg;
}
• RegistrationNo.java
public class RegistrationNo {
String regno; }
• Textcar.java
public class TestCar {
public static void main(String[] args) {
Car c = new Car();
c.model="BMW";
c.reg.regno="ASDASD";
} }
5/5/2021 Selenium Webdriver 2.0 174
POM
• Page Factory is a class
• Twitter.com
• More successful where application have similar pages
• Create package com.learning.twitter.pages
• Configure project for
• Selenium
• Design Twitter Login page class
5/5/2021 Selenium Webdriver 2.0 175
POM
Let’s create login functionality with POM framework and run
TwitLoginPage.java
public class TwitLoginPage {
@FindBy(xpath="//*[@id='signin-email']")
public WebElement username;
@FindBy(xpath="//*[@id='signin-password']")
public WebElement password;
@FindBy(xpath="//*[@id='front-container']/div[2]/div[2]/form/table/tbody/tr/td[2]/button")
public WebElement singin;
public void doLogin(String myusername, String mypassword)
{
username.sendKeys(myusername);
password.sendKeys(mypassword);
singin.click();
}
}
5/5/2021 Selenium Webdriver 2.0 176
POM
• testTwitLoginPage.java
public class testTwitterLoginPage {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://twitter.com");
TwitLoginPage lp = PageFactory.initElements(driver,
TwitLoginPage.class);
lp.doLogin("rishikeshmemane@yahoo.com", "Anupam$100");
} }
5/5/2021 Selenium Webdriver 2.0 177
POM
• Login page HAS A landing page
• Create TwitLandingpage.java
• Create 4 FindBy WebElements
• Profile
• Tweets
• Following
• Followers
• And create 4 different methods each corresponding to each
method.
• For doLogin method, have TwitLoginPage as return type
• And return
PageFactory.initElements(driver,TwitLoginPage.class);
• Create constructor for both classes which will define driver
with one parameter as driver
5/5/2021 Selenium Webdriver 2.0 178
POM
• Complete Picture/FLow
5/5/2021 Selenium Webdriver 2.0 179
POM
testTwitterLoginPage.java
WebDriver driver = new FirefoxDriver();
driver.get("http://twitter.com");
TwitLoginPage lp = PageFactory.initElements(driver,
TwitLoginPage.class);
TwitLandingPage landingPage =
lp.doLogin("rishikeshmemane@yahoo.com", "Anupam$100");
landingPage.gotoProfile();
Run and check if it successful.
Lets automate some more functionalities in twitter.com
5/5/2021 Selenium Webdriver 2.0 180
POM
TwitLandingPage.java
public class TwitLandingPage {
WebDriver driver;
//constructor
public TwitLandingPage(WebDriver driver)
{ this.driver = driver; }
@FindBy(xpath="//*[@id='page-container']/div[1]/div[1]/div/div[2]/div/a")
public WebElement profile;
@FindBy(xpath="//*[@id='page-container']/div[1]/div[1]/div/div[3]/ul/li[1]/a/span[1]")
public WebElement tweets;
@FindBy(xpath="//*[@id='page-container']/div[1]/div[1]/div/div[3]/ul/li[2]/a/span[1]")
public WebElement following;
@FindBy(xpath="//*[@id='page-container']/div[1]/div[1]/div/div[3]/ul/li[3]/a/span[1]")
public WebElement followers;
public TwitMyProfile gotoProfile()
{
profile.click();
return PageFactory.initElements(driver, TwitMyProfile.class);
}
public void gotoTweets()
{}
public void gotoFollowing()
{}
public void followers()
{}
}
5/5/2021 Selenium Webdriver 2.0 181
POM
• Create TwitMyProfile.java
public class TwitMyProfile {
@FindBy(xpath="")
public WebElement editbutton;
WebDriver driver;
public TwitMyProfile(WebDriver driver)
{
this.driver = driver;
}
public TwitEditProfile editProfile()
{
editbutton.click();
return PageFactory.initElements(driver, TwitEditProfile.class);
}
5/5/2021 Selenium Webdriver 2.0 182
POM
• Create TwitEditProfile.java
public class TwitEditProfile {
WebDriver driver;
public TwitEditProfile(WebDriver driver)
{ this.driver = driver; }
@FindBy(xpath="")
public WebElement inlinediticon;
@FindBy(xpath="")
public WebElement uploadPhoto;
@FindBy(xpath="")
public WebElement applyButton;
@FindBy(xpath="")
public WebElement cancelButton;
public void changePic()
{
inlinediticon.click();
uploadPhoto.sendKeys("E:tempscreenshota.jpg");
applyButton.click();
cancelButton.click();
}
public void changeTitle()
{ }
public void caangeSummary()
{ }
}
5/5/2021 Selenium Webdriver 2.0 183
POM
• Main method
public class testTwitterLoginPage {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://twitter.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
TwitLoginPage lp = PageFactory.initElements(driver, TwitLoginPage.class);
// encapsulation TwiLoginPage Has a LandingPage
TwitLandingPage landingPage = lp.doLogin("rishikeshmemane@yahoo.com",
"Anupam$100");
TwitMyProfile profile = landingPage.gotoProfile();
TwitEditProfile editprofile = profile.editProfile();
editprofile.changePic();
}
}
5/5/2021 Selenium Webdriver 2.0 184
Useful Links/References
• http://yizeng.me/2014/04/25/relationships-between-different-
versions-of-selenium/
• http://seleniumeasy.com/
• http://www.toolsqa.com/
• http://www.w3schools.com/cssref/css_selectors.asp
• http://www.w3schools.com/js/default.asp - JavaScript
5/5/2021 Selenium Webdriver 2.0 185
Documentation
• Seleniumhq.org
• How to import JAVA documentation in Eclipse?
• Copy link from http://docs.seleniumhq.org/download/ web
page JavaDoc link
• Go to Project->Properties->Java Build Path->Libraries-
>Selenium-Java<version>
• Edit and paste the copied url removing index.html
• Now when mouse is moved on class, help will be shown
inline.
5/5/2021 Selenium Webdriver 2.0 186
Short Keys
5/5/2021 Selenium Webdriver 2.0 187
ShortKey Action
Ctrl+Shift+o Import required classes
Alt_Shift+q,c Opens Console
Alt+Shift+x,n Run as TestNG test case
Ctrl+F11 Run test case as Java application
Switch Workspace Alt F+W
To Open IDE CTRL+Alt+S
Thank You
• Email-id: Rishiscorporatetraining@gmail.com
• Cell# : +91-9552588168
5/5/2021 Selenium Webdriver 2.0 188
Exercise
• Login to yahoomail.com
• Open a browser, maximize, print window Title
• Cucumber exercise for one feature and step file
• Print Facebook friends name
• Only testing site exercise
5/5/2021 Selenium Webdriver 2.0 189
Exercise – Finding links from google.com
WebDriver dr = new FirefoxDriver();
dr.get("http://google.com");;
dr.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
dr.findElement(By.name("q")).sendKeys("mumbai");
dr.findElement(By.name("q")).sendKeys(Keys.ENTER);
WebElement box = dr.findElement(By.xpath("//*[@id='rso']"));
List<WebElement> links = box.findElements(By.tagName("a"));
int totLinks = links.size();
System.out.println("total links: " + totLinks);
for(int i=0;i<totLinks;i++)
{
if ( links.get(i).isDisplayed() && !(links.get(i).getText().isEmpty()) )
System.out.println(links.get(i).getText() + " -- " +
links.get(i).isDisplayed() + " -- " + links.get(i).isEnabled());
}
5/5/2021 Selenium Webdriver 2.0 190
Exercise – Autosuggestion from google.com
public static WebDriver dr=null;
public static void main(String[] args) throws InterruptedException
{
dr = new FirefoxDriver();
dr.get("http://google.com");;
dr.findElement(By.name("q")).sendKeys("mumbai");
Thread.sleep(3000L);
String part1 = "//*[@id='sbse";
String part2 = "']/div[2]";
int i=0;
while(iselementPresent(part1+i+part2))
{
String xpath = part1+i+part2;
System.out.println(dr.findElement(By.xpath(xpath)).getText());
i++;
}
dr.quit();}
public static boolean iselementPresent(String pXpath)
{
int cnt=0;
cnt = dr.findElements(By.xpath(pXpath)).size();
if (cnt == 0)
return false;
else
return true;
}
5/5/2021 Selenium Webdriver 2.0 191
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentation
Selenium web driver_2.0_presentation

Más contenido relacionado

La actualidad más candente

Introduction to Android programming
Introduction to Android programmingIntroduction to Android programming
Introduction to Android programmingSirwan Afifi
 
Android study jams
Android study jamsAndroid study jams
Android study jamsGDSCIIITR
 
Exploring Android Studio
Exploring Android StudioExploring Android Studio
Exploring Android StudioAkshay Chordiya
 
Introduction to Android Studio
Introduction to Android StudioIntroduction to Android Studio
Introduction to Android StudioMichael Pan
 
Anroid Tutorial Beginner level By SAMRAT TAYADE
Anroid Tutorial Beginner level By SAMRAT TAYADE Anroid Tutorial Beginner level By SAMRAT TAYADE
Anroid Tutorial Beginner level By SAMRAT TAYADE Samrat Tayade
 
Generating efficient APK by Reducing Size and Improving Performance
Generating efficient APK by Reducing Size and Improving PerformanceGenerating efficient APK by Reducing Size and Improving Performance
Generating efficient APK by Reducing Size and Improving PerformanceParesh Mayani
 
Android 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndroid 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndy Scherzinger
 
Android – As a tool of innovation
Android – As a tool of innovation Android – As a tool of innovation
Android – As a tool of innovation Pallab Sarkar
 
Project a day 2 introduction to android studio
Project a day 2   introduction to android studioProject a day 2   introduction to android studio
Project a day 2 introduction to android studioGoran Djonovic
 
Flutter dhaval solanki
Flutter   dhaval solankiFlutter   dhaval solanki
Flutter dhaval solankiDhaval Solanki
 
[Android] Introduction to Android Programming
[Android] Introduction to Android Programming[Android] Introduction to Android Programming
[Android] Introduction to Android ProgrammingNikmesoft Ltd
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to androidKalpesh Patel
 
Project presentation (Loginradius SDK for Android)
Project presentation (Loginradius SDK for Android)Project presentation (Loginradius SDK for Android)
Project presentation (Loginradius SDK for Android)shwetarathi Rathi
 
Ios driver presentation copy
Ios driver presentation copyIos driver presentation copy
Ios driver presentation copyDavid O'Dowd
 
10 Usability Heuristics - IntelliJ IDEA
10 Usability Heuristics - IntelliJ IDEA10 Usability Heuristics - IntelliJ IDEA
10 Usability Heuristics - IntelliJ IDEANirodha Perera
 

La actualidad más candente (20)

Introduction to Android programming
Introduction to Android programmingIntroduction to Android programming
Introduction to Android programming
 
Android study jams
Android study jamsAndroid study jams
Android study jams
 
Exploring Android Studio
Exploring Android StudioExploring Android Studio
Exploring Android Studio
 
Introduction to Android Studio
Introduction to Android StudioIntroduction to Android Studio
Introduction to Android Studio
 
Anroid Tutorial Beginner level By SAMRAT TAYADE
Anroid Tutorial Beginner level By SAMRAT TAYADE Anroid Tutorial Beginner level By SAMRAT TAYADE
Anroid Tutorial Beginner level By SAMRAT TAYADE
 
Generating efficient APK by Reducing Size and Improving Performance
Generating efficient APK by Reducing Size and Improving PerformanceGenerating efficient APK by Reducing Size and Improving Performance
Generating efficient APK by Reducing Size and Improving Performance
 
Android 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndroid 101 - Introduction to Android Development
Android 101 - Introduction to Android Development
 
Android – As a tool of innovation
Android – As a tool of innovation Android – As a tool of innovation
Android – As a tool of innovation
 
Project a day 2 introduction to android studio
Project a day 2   introduction to android studioProject a day 2   introduction to android studio
Project a day 2 introduction to android studio
 
Flutter dhaval solanki
Flutter   dhaval solankiFlutter   dhaval solanki
Flutter dhaval solanki
 
[Android] Introduction to Android Programming
[Android] Introduction to Android Programming[Android] Introduction to Android Programming
[Android] Introduction to Android Programming
 
Introduction to android
Introduction to androidIntroduction to android
Introduction to android
 
Fire up your mobile app!
Fire up your mobile app!Fire up your mobile app!
Fire up your mobile app!
 
Project presentation (Loginradius SDK for Android)
Project presentation (Loginradius SDK for Android)Project presentation (Loginradius SDK for Android)
Project presentation (Loginradius SDK for Android)
 
Ide presentation
Ide presentationIde presentation
Ide presentation
 
Ios driver presentation copy
Ios driver presentation copyIos driver presentation copy
Ios driver presentation copy
 
BCS Selenium Workshop
BCS Selenium WorkshopBCS Selenium Workshop
BCS Selenium Workshop
 
10 Usability Heuristics - IntelliJ IDEA
10 Usability Heuristics - IntelliJ IDEA10 Usability Heuristics - IntelliJ IDEA
10 Usability Heuristics - IntelliJ IDEA
 
Ide description
Ide descriptionIde description
Ide description
 
Android Studio vs. ADT
Android Studio vs. ADTAndroid Studio vs. ADT
Android Studio vs. ADT
 

Similar a Selenium web driver_2.0_presentation

Tools for Software Testing
Tools for Software TestingTools for Software Testing
Tools for Software TestingMohammed Moishin
 
Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully Applitools
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfullyTEST Huddle
 
How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)Dave Haeffner
 
Effective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperEffective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperMike Melusky
 
Effective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperEffective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperMike Melusky
 
Best selenium training eduxfactor
Best selenium training   eduxfactorBest selenium training   eduxfactor
Best selenium training eduxfactoreduxfactor .com
 
Best selenium training institute in hyderabad
Best selenium training institute in hyderabadBest selenium training institute in hyderabad
Best selenium training institute in hyderabadVamsiNihal
 
Selenium training eduxfactor
Selenium training   eduxfactorSelenium training   eduxfactor
Selenium training eduxfactorSayyedYusufali
 
best selenium training institute in hyderabad
best selenium training institute in hyderabadbest selenium training institute in hyderabad
best selenium training institute in hyderabadDIGITALSAI1
 
Best selenium training institute in hyderabad
Best selenium training institute in hyderabadBest selenium training institute in hyderabad
Best selenium training institute in hyderabadVamsiNihal
 
best selenium training institute in hyderabad
best selenium training institute in hyderabadbest selenium training institute in hyderabad
best selenium training institute in hyderabadDIGITALSAI1
 
software testing training institute in hyderabad
software testing training institute in hyderabadsoftware testing training institute in hyderabad
software testing training institute in hyderabadKhalidQureshi31
 
selenium with python training
selenium with python trainingselenium with python training
selenium with python trainingSaiprasadVella
 
Selenium training eduxfactor-converted
Selenium training   eduxfactor-convertedSelenium training   eduxfactor-converted
Selenium training eduxfactor-convertedSayyedYusufali
 
selenium with python training
selenium with python trainingselenium with python training
selenium with python trainingSaiprasadVella
 
Selenium training eduxfactor
Selenium training   eduxfactorSelenium training   eduxfactor
Selenium training eduxfactorSayyedYusufali
 
best selenium training institute in Hyderabad
best selenium training institute in Hyderabadbest selenium training institute in Hyderabad
best selenium training institute in HyderabadSaiprasadVella
 

Similar a Selenium web driver_2.0_presentation (20)

Automated ui-testing
Automated ui-testingAutomated ui-testing
Automated ui-testing
 
Tools for Software Testing
Tools for Software TestingTools for Software Testing
Tools for Software Testing
 
Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfully
 
How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)
 
Effective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperEffective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and Dapper
 
Effective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperEffective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and Dapper
 
Introduction to selenium
Introduction to seleniumIntroduction to selenium
Introduction to selenium
 
Best selenium training eduxfactor
Best selenium training   eduxfactorBest selenium training   eduxfactor
Best selenium training eduxfactor
 
Best selenium training institute in hyderabad
Best selenium training institute in hyderabadBest selenium training institute in hyderabad
Best selenium training institute in hyderabad
 
Selenium training eduxfactor
Selenium training   eduxfactorSelenium training   eduxfactor
Selenium training eduxfactor
 
best selenium training institute in hyderabad
best selenium training institute in hyderabadbest selenium training institute in hyderabad
best selenium training institute in hyderabad
 
Best selenium training institute in hyderabad
Best selenium training institute in hyderabadBest selenium training institute in hyderabad
Best selenium training institute in hyderabad
 
best selenium training institute in hyderabad
best selenium training institute in hyderabadbest selenium training institute in hyderabad
best selenium training institute in hyderabad
 
software testing training institute in hyderabad
software testing training institute in hyderabadsoftware testing training institute in hyderabad
software testing training institute in hyderabad
 
selenium with python training
selenium with python trainingselenium with python training
selenium with python training
 
Selenium training eduxfactor-converted
Selenium training   eduxfactor-convertedSelenium training   eduxfactor-converted
Selenium training eduxfactor-converted
 
selenium with python training
selenium with python trainingselenium with python training
selenium with python training
 
Selenium training eduxfactor
Selenium training   eduxfactorSelenium training   eduxfactor
Selenium training eduxfactor
 
best selenium training institute in Hyderabad
best selenium training institute in Hyderabadbest selenium training institute in Hyderabad
best selenium training institute in Hyderabad
 

Último

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 

Último (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 

Selenium web driver_2.0_presentation

  • 1. Introduction • Rishikesh – Trainer’s Profile • Your introduction • Name, Total Experience, Tenure in current organization, Aspiration, Automation exposure 5/5/2021 Selenium Webdriver 2.0 1
  • 2. Rishikesh – Trainer’s Profile • Rishikesh has close to 15 years of IT Experience • Masters in Computer Science from Pune University • Certifications – PMP, CSQA, CSM, ITIL • Organizations – Tech Mahindra, Syntel, BMC Software, IBM • Last designation - Sr. Test Manager in Tech Mahindra • Handled very large teams - 150 members and worked with product and service industry • Was part of TCoE, PreSales, Deliver management • Currently hold a training consultancy – Vedant Consultancy in Pune • Conducted numerous corporate trainings in Pune, Bangalore, seminars in different colleges. • Tools Expertise • Functional Testing • Selenium WebDriver.20 • UFT (Former name QTP) • AUTO IT • WebService API Testing • SOAPUI • Performance Testing • Jmeter • LoadRunner • Mobile Testing • Selendroid • Appium • Shell Scripting 5/5/2021 Selenium Webdriver 2.0 2
  • 3. Pre-Requisite to Learn Selenium • Programming language concepts • Basic knowledge of coding – any language • HTML knowledge – tag identification, Attributes etc. • XML knowledge for Selenium IDE • Java Script knowledge for IDE • Developer’s mindset – How to create/construct • Java or any Selenium supported language • Debugging skill • Learning attitude • Patience 5/5/2021 Selenium Webdriver 2.0 3
  • 4. Selenium Learning *** HAPPY LEARNING *** 5/5/2021 Selenium Webdriver 2.0 4
  • 5. FAQ From Beginners • What is Selenium? • Selenium is a suite of tools to automate web browsers across many platforms. • What all browser Selenium supports? • IE, Chrome, Firefox, Android, iPhone • What all languages are supported by Selenium? • Java, C#, Ruby, Python, Perl, PHP • Is it mandatory to write test script in same language in which software is made? • No • Why is Selenium is getting popular in market? • Open source, wide blogs/forum, Google support • Is it mandatory to learn Java in depth to master in Selenium? • No • What are course contents? What all topics will be covered in the course? • Can I use IDE component to automate complete product/project? • How much time would I require to learn Selenium? • Learning – 1 week • Intermediate 3 months • Expertise – 6 months to 1 year • Practice Practice and Practice is a key to learn any automation tool. 5/5/2021 Selenium Webdriver 2.0 5
  • 6. Testing All About • What is testing? Use of Testing? • Discovering defects and finding enhancement to the product • Fit for use • Conformance to the requirement • What is manual Testing? • What is Automation Testing? • Convert manual actions into automated actions with verifications • Advantages of Automation Testing • Consistency output: Increased repeatability • Data sensitive test cases • Lengthy test cases • Less time to market • Support to Browser/OS/Database • Higher Test coverage • Various Tools • Proprietary – QTP/UFT, Rational Robot, SilkTest , Testcomplete, VSTP • Open source – Selenium, SOAPUI, AUTOIT, Watir, 5/5/2021 Selenium Webdriver 2.0 6
  • 7. JAVA – Object Oriented Programming • How to download and install Java? • Google->Download Java • Verify if Java is installed: C:programFilesJava folder presence • What is IDE – Integrated Development Environment? • What is Eclipse? How to download and install Eclipse? • Google->Download Eclipse->Eclipse IDE for Java Developers (~212 MB) – 32 or 64 bit windows version • Eclipse is an exe file, does not need to install • Double click on Eclipse.exe to open Eclipse • What is Workspace? • A work area where test scripts are stored through Eclipse • Open Eclipse • Project Explorer, Java Perspective, • Increase font size • Go to Windows->Preferences->General->Appearances->Colors and fonts • File->New Project->Java Project-> <project name> • Expand project folder in Solution Explorer and find SRC folder (Source) contains all Java scripts • Right click on Project name in Solution Explorer->Java Properties – finds all project’s properties • Check project on disk system • Create first Java class in Java Project • Check java class on physical disk system • Understand first program • Comments – // or /* */ why to have comments in program? • Java case sensitive language • Auto suggestion available in IDE – Eclipse – Advantage over writing program in notepad • Run program 1. right click on class file in solution explorer and run as Java application • 2. Run by pressing right triangle 5/5/2021 Selenium Webdriver 2.0 7
  • 8. JAVA – Object Oriented Programming • Short cut to write syso + Control + spacebar - System.out.println • Difference between System.out.println and System.out.print • Extension of java file is .JAVA • Extension of compile JAVA program is .class (Byte code) • .class file can be executed on any platform. Windows .class file can be executed on Unix and vice-versa. • How to debug a program in Java using Eclipse? • F8 step by step execution 5/5/2021 Selenium Webdriver 2.0 8
  • 9. JAVA – Object Oriented Programming • Open Source • Sun Microsystem and now Oracle • Object Oriented Programming • Inheritance: IS A relationaship, CAR IS A VEHICLE • Polymorphism • Overloading • Overriding • Encapsulation: HAS A relationship, Building HAS A room • Class Concept : Skeleton • Interface Concept: Contract 5/5/2021 Selenium Webdriver 2.0 9
  • 10. JAVA – Object Oriented Programming • Case Sensitive and platform independent • Blue colored words are keyword • Java dataTypes • char, int, long, float, double, Boolean • Comparison operators - >, <, <=, >=, != • Logical operators - &&, ||, ! • if condition has to be written in brackets - () • Find out greatest of 2 numbers • Find out greatest of 3 numbers. • String is inbuilt class in Java • Control Structure • If, if else • Find largest of 2 and 3 numbers • For • While • Arrays • One dimensional – definition, initialization, printing, length • Two dimensional - 5/5/2021 Selenium Webdriver 2.0 10
  • 11. JAVA – Object Oriented Programming • Array examples using char, int, string • Drawbacks of array • What are functions? • Function parameters – By Value and By Reference • Function return types • Local Variable – loop variables, block variables, main method variables • Global Variable – Class member • Meaning of Static variable or method? • Common memory allocated to static variable or method • Object and object reference • Constructor 5/5/2021 Selenium Webdriver 2.0 11
  • 12. Constructor • Used to initialize members (Non static) • Can have ZERO or more no of parameters • Automatically called when object is created • Constructor do not have return type, void and should have same name as of class • Example: • Car c= new Car() // constructor is called when object is created • Public car() • { this.model=“BMW”;} • Constructor Overloading • Same name with different parameter types 5/5/2021 Selenium Webdriver 2.0 12
  • 13. Class & Object Concept Public class Car{ String model; int price; Static wheels; Public static start(){ System.out.println(“Starting : “ + model); Public static stop(){ System.out.println(“Stopping : “ + model); } Public static void main(String args[]) { Car c1 = new Car(); C1.model=4000000; C1.model=“Audi”; Car.wheels=4; } 5/5/2021 Selenium Webdriver 2.0 13 Model Price Start() Stop() c1 wheels Model and price are non static Wheels is static resides in common memory & is NOT part of object Static variable
  • 14. Inheritance • Inheritance derives it parents characteristics Public class Car() { int price; Public void start();{System.out.println(“Starting Car”); Public void stop();{System.out.println(“Stopping Car”);} Public class BMW() extends Car {Public void theftsafety();{System.out.println(“BMW theftsafety…”); Public void start();{System.out.println(“Starting BMW”); // Overridden method} • BMW class object reference can access Car class’s global variable/members and methods. • Car class is called Super or Parent class • BMW class is child or sub class. Car c=new Car(); c.price=10; c.start(); c.theftsafety(); NOT ALLOWED BMW b=new BMW();b.price=20;b.start();b.theftsafety(); • When object instance is created, constructor of parent and child class is executed. 5/5/2021 Selenium Webdriver 2.0 14 CAR BMW
  • 15. Overridden Method • Same method is implemented in parent and child class. • Method implemented in sub class is called overridden method. • If BMW class has below method which is already present in Car class. • Public void start();{System.out.println(“Starting Car”);} • Car c = new Car(); • BMW b = new BMW(); • c.start(); This will invoke start method from Car class. • b.start(); This will invoke start method from BMW class. 5/5/2021 Selenium Webdriver 2.0 15
  • 16. Object • Meaning of below object creation? Car c1 = new BMW(); • C1. can call all methods from Car call (Parent class) But can not call methods defined only in child class. • Overridden function can be called from child class. • c1.start() Overridden method called from BMS class • c1.stop() Car method is called • c1.theftsafty NOT ALLOWED 5/5/2021 Selenium Webdriver 2.0 16
  • 17. Interface • Is a abstract class • Does not have implementation of method • Declares required methods • Can not create instance of an interface • Static function declaration is not allowed • Initialization of variables is mandatory. • Variable are static in nature. • Example Public interface Bank { Int minBalance=5000; Public void transferMoney(); Public void Credit();Public void Debit();} TestBank.java Bank b = new Bank(); NOT ALLOWED HSBCBank.java Public class HSBCBank implements Bank{ Have to implement all methods in parent class in order to create an instance of inherited class i.e. HSBCBank else it again becomes interface. Can we define new method in HSBCBank and call it from testBank.java? NO TestBank.java Bank b = new HSBCBank(); b.credit(); b.debit(); b.transfermoney(); System.out.println(b.minBalance); System.out.println(Bank..minBalance); 5/5/2021 Selenium Webdriver 2.0 17
  • 18. Package • Package is nothing but sub folder • Logical grouping of modules/functionality • Pgk1 Public class Login() { public void adminLogin(){ System.out.println(“Logging as ADMIN user….”);} • Pgk2 Public class Test{ public static void main(String args[]){ Login l = new Login(); // Require to import Login.adminLogin L.adminLogin();} 5/5/2021 Selenium Webdriver 2.0 18
  • 19. Access Modifiers • Public • Accessible from everywhere • Within and outside class • Within and outside package • Private • Accessible from the current package • Default • Accessible from the current package • Protected • Accessible in current package and all child classes 5/5/2021 Selenium Webdriver 2.0 19
  • 20. Exception Handling Try { System.out.println(“A”); Int I = 10/0; // divide by Zero exception raised System.out.println(“B”); } catch (Exception e) { System.out.println(“Error Occurred ” + e.getMessage()); System.out.println(“C”); e.printStackTrace(); // prints error } • In case of error/exception, control comes to catch block of try- catch block. • Output • A and Error Occurred then C 5/5/2021 Selenium Webdriver 2.0 20
  • 21. Exception Handling • Int arr[] = new int[3]; • Arr[3]=12; // will error out ArrayIndexOutofBoundsException • Instead of try-catch block one can use throws clause/declaration • Example Public static void main(String[] args) throws InterruptedException {clickLink();} Public static void clickLink() throws InterruptedException {loadPage();} Public static void loadPage() throws InterruptedException {Thread.sleep(4000L);} • Throwable is a super class and Error and Exception are child classes. 5/5/2021 Selenium Webdriver 2.0 21
  • 22. Throw & finally, final clause • throw new Exception(“Some Exception”); • Use of throw is to skip test case based on certain condition. • Finally clause Executes finally block irrespective of error Try { int i=10/0; } catch(Exception e) { e.printStackTrace();} finally{ closeDBConnection();} • Final int a = 100; // declare as constant a=200; NOT allowed 5/5/2021 Selenium Webdriver 2.0 22
  • 23. Collection API • ArrayList • Removes drawback of fixed no of elements • Dynamically growing data structure • ArrayList contains one data type • Index starts with ZERO • ArrayList<String > list = new ArrrayList<String>(); • List.add(“Pune”); • List.add(“Mumbai”) • System.out.println(list.get(1)); // extract 1st element i.e. Mumbai • List.size() – Returns current size of list • Print all list elements • for (int i=0;i<list.size();i++) • System.out.println(list.get(i)); • Example: Store all links present on web page, Total no of links are known dynamically. 5/5/2021 Selenium Webdriver 2.0 23
  • 24. HashTable • HashTable is inbuilt class • Dynamically growing data structure • HashTable has key, value pair • No index available • Key in hashtable is unique • HashTable<String,String> table = new HashTable<String,String> (); • table.put(“name”,”Ankit”); • table.put(“place”,”India”); • table..put(“profession”,”IT”) • System.out.println(table.get(“name”)); // Ankit • System.out.println(table.get(“place”)); /India • Use HashTable – Test Data can be stored in Selenium. 5/5/2021 Selenium Webdriver 2.0 24
  • 25. Set • Data Structure • Holds multiple values • Set<String> mySet = new HashSet<String>(); • mySet.add(“India”); • mySet.add(“UK”); • mySet.add(“USA”); • mySet.add(“China”); • Elements are added • No index, no order • Unique value present, no duplicates allowed • mySet.size() – total elements present 5/5/2021 Selenium Webdriver 2.0 25
  • 27. Selenium Introduction • What is Selenium? • Automates web applications across many browsers • Library by Google (former name Thoughtworks) • Javascript based automation engine • Jason Higgins – Thoughtworks 2004 – Core Selenium library • Simon Stewart – Google a creator of WebDriver • Selenium 1. 0 – Focused on Remote Control • Selenium 2.0 – Focused on Webdriver 2.0, released in Jul 2011 • Selenium 3.0 – Extending Webdriver 2.0 to cope up with Android functionalities – mobile testing, Selendroid and Appium – To be released in Dec-2015 • Support many Languages • Java, Python, C#, Ruby, JavaScript • Supported Browser • Firefox, IE, chrome, iPhoneDriver, HTMLDriver, AndroidDriver • OS support • Windows, Linux, Unix 5/5/2021 Selenium Webdriver 2.0 27
  • 30. Selenium Language Support 5/5/2021 Selenium Webdriver 2.0 30
  • 31. Selenium Browser Support 5/5/2021 Selenium Webdriver 2.0 31
  • 32. Selenium OS Support 5/5/2021 Selenium Webdriver 2.0 32
  • 33. Selenium Framework Support 5/5/2021 Selenium Webdriver 2.0 33
  • 34. Selenium Overview • Four components of Selenium • IDE – Integrated Development Environment • Selenium Remote Control (RC) • WebDriver 2.0 • GRID 2 • Basic component - IDE • Add on to Firefox only • Record and play • Remote Control – Deprecated • Prior version of Selenium WebDriver 2.0 • Need to start Selenium server • Contain only one class • GRID 2.0 • Used for parallel test case execution on multiple machines 5/5/2021 Selenium Webdriver 2.0 34
  • 35. Selenium Webdriver 2.0 • What is WebDriver? • Is and Interface • Has many functions/methods like getTitle,get,navigate • Download and configuration of Selenium JAR files • Architecture of Selenium • FirefoxDriver,ChromeDirver implements WebDriver • Drivers for Firefox, IE, Chrome, Iphone, Android, HTMLUnitDriver • Selenium Remote Control (RC) • Firefox Profile • Use of Firefox profile 5/5/2021 Selenium Webdriver 2.0 35
  • 36. FireBug and Firepath Addons • Firepath and Firebug • Inspecting elements using Firefox, Chrome, IE • Identifying webElement/component on webpage • Locators • Id,name,class,cssSelector,xpath,LinkText,PartialLinkT ext • What is xpath? • Absolute, partial • Creating custom xpath • Handling dynamic xpath • First Selenium test script • Difference between close and quit • Importing webDriver documentation in Eclipse 5/5/2021 Selenium Webdriver 2.0 36
  • 37. FireBug and Firepath Addons • What is Firebug and Firepath? • Add-ons to Firefox browser to find out address of webelement on webpage • Xpath, CssSelector useful to find firebug & firepath • How to download and install Firebug? • Google download Firebug • Click on first link and download (Green button allows you to download Firebug) and install • Google download Firepath and download(Green button allows you to download Firebug) and install . Restart Firefox browser 5/5/2021 Selenium Webdriver 2.0 37
  • 38. FireBug and Firepath Addons • You can see bug icon at the right top corner of Firefox browser as below • How to find out xpath of a webelement? • Open gmail.com • Click on bug icon at top right corner of firefox • Window at bottom will appear as below 5/5/2021 Selenium Webdriver 2.0 38
  • 39. FireBug and Firepath Addons • Red color box at button shows xpath of input field Enter Your email 5/5/2021 Selenium Webdriver 2.0 39
  • 40. IDE • What is IDE? • Integrated Development Environment • Who should use IDE • Beginner to understand how Selenium codes • How various xpaths are formed for a web element • Advantages of IDE • Record and play • Helpful to find IDE if you are not able to customize of generate xpath using Firebug • Disadvantages of IDE • Dynamic xpaths are problematic. • Modification to existing script is bit difficult 5/5/2021 Selenium Webdriver 2.0 40
  • 41. IDE 5/5/2021 Selenium Webdriver 2.0 41 IDE Remote Control WebDriver 2.0 Record and Play Need to code in Java Need to Code in Java Works for Firefox only Works on all browsers Works on all browsers Applicable to small projects Applicable to large/huge projects Applicable to large/huge projects Helps to find xpaths Need to find xpaths using firebug/firepath or customize Need to find xpaths using firebug/firepath or customize Java Script optional Core Java,Ruby,C#,Python required Core Java,Ruby,C#,Python required Addon to Firefox Selenium Component Selenium component In Use Deprecated In Use No programming language required to record script Programming langugage required to code Programming langugage required to code First Component developed Second component developed Latest component developed Used to create a script to check production defect Used to create regression or functional test case Used to create regression or functional test case
  • 42. Installation of IDE • Selenium IDE is addon to Firefox browser. • Go to seleniumhq.org • Go to Download link • Check for Selenium IDE section and click on 2.9.0 link (latest version) • Click on Install • Go to Firefox browser • Click on Tools and check if Selenium IDE option appears 5/5/2021 Selenium Webdriver 2.0 42
  • 43. IDE • By default recording mode is on. • Can directly record user actions by navigating to any website in Firefox browser. • Record opening salesforce.com • Open command – Opens URL in browser • Click – click on the webelement • Type – type text into the web element • clickAndWait – Click and wait • Save Test – saves HTML document format • Run the test and see playing back. • Able to convert manual actions into automated script with help of IDE. 5/5/2021 Selenium Webdriver 2.0 43
  • 45. IDE • Various Xpaths (Address of webelement) of Login button • //*[contains(text(),'Login') and @href='https://login.salesforce.com'] -> (by.xpath) • id=button-login ->(By.id) • //a[contains(text(),'Login')] ->(by.xpath) • css=#button-login -> CssSelector • //a[@id='button-login'] ->(by.xpath) • //ul[@id='lang-select']/li[1]/a ->(by.xpath) • //a[contains(@href, 'https://login.salesforce.com')] ->(by.xpath) • One webElement can be identified by multiple xpaths • One unique xpath can not point to more than one webelement • One xpath (not unique) can point to more than one webelement. (//ul[2]/li  9 matches on salesforce.com page) • To convert above xpath to point to unique webelement • Add tag at the end and/or • Add attributes to xpath using and condition. • //ul[2]/li[1]/a[@id='button-login'] 5/5/2021 Selenium Webdriver 2.0 45
  • 46. IDE • HTML document format of a test case in browser 5/5/2021 Selenium Webdriver 2.0 46
  • 47. IDE • Test case to automate webmath.com • Go www.webmath.com • Click on 5/5/2021 Selenium Webdriver 2.0 47
  • 48. IDE • From the recorded Login test script, remove clickAndWait command and run the script to get “Element [//*[id=‘username’] not found error” • ClickAndWait will wait until the complete page is loaded upon clicking of the web element. Default wait time in Selenium is 30 seconds. • IF element is not found within 30 seconds script will error out and script will be halted. • The statement in IDE becomes red wherever error occurs. 5/5/2021 Selenium Webdriver 2.0 48
  • 49. IDE • Double click statement and it will be executed. This is helpful to debug the script. • To debug program • Right click on the statement where you want to halt execution at run time and click on Toggle Breakpoint • At run time, after script is stopped at the breakpoint, Step button will be used to execute one statement at a time. • Code can be executed line by line to debug any script. • Speed of test script execution can be made slow using slider. 5/5/2021 Selenium Webdriver 2.0 49
  • 50. IDE • How to verify window title using verifyTitle command? • Insert command after Open command using right click and Insert. • In Command input field, type verifyTitle and in target type title. • Click on view source page on salesforce.com webpage, and find title string and paste this string in target field in IDE. • Run script and check if script passes • If you change title in the target field, and run script it will be failed, but script will not stopped running further statements. • Verify statements does not stop test script execution 5/5/2021 Selenium Webdriver 2.0 50
  • 51. IDE • How to verify window title using assertTitle command? • Insert command after Open command using right click and Insert. • In Command input field, type assertTitle and in target type title. • Click on view source page on salesforce.com webpage, and find title string and paste this string in target field in IDE. • Run script and check if script passes • If you change title in the target field, and run script it will be failed, and script will be executed further. • Assert command will halt test case execution and further statements in the test script will not be executed. 5/5/2021 Selenium Webdriver 2.0 51
  • 52. IDE • When to use verifyTitle or assertTitle? • If you want to stop further test script execution, use assertTitle. If the error is severe you should use assert else verify. • There are many verify commands like • verifyTitle • verifyText • verifyValue etc • Create a script by recording • Navigate www.webmath.com • Click on “Quick! I need help with: “ dropdown list • Enter any number in first input box • Select mile(s) per hour from next dropdown • Select kilometer(s) per hour • Click on Convert button • You will land on new page having answer for the problem • Stop recording and see the generated code 5/5/2021 Selenium Webdriver 2.0 52
  • 53. IDE • Original script • Now insert command (right click on selectAndWait command and click Insert New command)after open command to 1verify if “Go” button is present or not • Enter verifyElementPresent in command input field • Enter xpath of “Go” button as //*[@id='jumpToPage']/div/a/img • Now click on type command and right click to insert new command • Enter assertElementPresent in command input field • Enter //*[@id='d- childMainContLeft']/div[2]/table/tbody/tr/td[2]/font/b/form/center/p[3]/in put[1] in target input field. 5/5/2021 Selenium Webdriver 2.0 53
  • 54. IDE • So the final script will look like this • Run the script, it will be passed. • Change title and suffix 1 to title in target input field • Run the script verifyElementPResent will error out but script will run completely and test case result will be failed in Log. • The statement which was failed will be shown in red color. • Now revert title back to original by removing suffix 1 • Add suffix 1 to xpath of assertElementPresent command • Run the script and script will failed at assertElementPresent command and will halt without executing further statements and test case result shown in Log will be failed. 5/5/2021 Selenium Webdriver 2.0 54
  • 55. IDE • Passed test result as below 5/5/2021 Selenium Webdriver 2.0 55
  • 56. IDE • Add last command as verifyText in command input • Target is //html/body/font/font/font/center • Value is You want to convert 5 mile(s) per hour to kilometer(s) per hour. Here's how: • Run test script and see it should be passed. • Final test script looks like 5/5/2021 Selenium Webdriver 2.0 56
  • 57. IDE • Customize commands in IDE using extensions • Control loops – if, while can be written with the help of extension in IDE. • Where to get extensions? • Seleniumhq.org->Documentation->Selenium IDE->Sequence of Evaluation and Flow Control ->goto_sel_ide.js extension->page- >github.com/73rhodes/sideflow->Download.zip • Save it in a folder • Unzip folder • Slideflow.js is the only required java script (.js) file • In IDE, go to Tools->Options->Browse-> Provide the file name Slideflow.js • Close IDE using File->Exit and restart • Now command field should have while command present in dropdown list. • What is salesforce.com website • Login • Create Lead for potential customers 5/5/2021 Selenium Webdriver 2.0 57
  • 58. IDE • Variable concept in IDE • Command Target Value Comment • store 100 b Store b = 1000 • echo ${b} Display 1000 • echo Value of b = ${b} Display Value of b=1000 • echo javascript{storeVars[‘b’]} Display 1000 • Store javascript(storeVars[‘b’]) d store value of b to d i.e. 1000 • echo ${d} Display 1000 • storeEval storedVars[‘b’] e Store e=b, e will have 1000 • echo ${e} display e as 1000 • storeEval new Number(storedVars['b'])+10 f • echo ${f} display f as 1010 5/5/2021 Selenium Webdriver 2.0 58
  • 59. IDE • Parameterization using XML files in IDE 5/5/2021 Selenium Webdriver 2.0 59
  • 60. Locators • What is locator? • Locator helps to identify element on a webpage. 1. id 2. linktext 3. partialLinkText 4. name 5. tagName 6. className 7. cssSelector 8. Xpath Priority usage of locator: 1. Id is the fastest way to locate web element 2. Xpath 3. cssSelector in case of IE and chrome Examples are in Notes section 5/5/2021 Selenium Webdriver 2.0 60
  • 61. Xpath • Xpath is the address of a webelement • Syntax - //*[@attribute=‘attribute value’] • Absolute xpath • Full xpath starts with html/body/ • Identify web element Username on gmail.com • html/body/div/div[2]/div/div/form/div[1]/div/div/div/div/inp ut[1] • Identify web element Next button on gmail.com • //html/body/div/div[2]/div[2]/div/form/div/div/input[@value ='Next'] • Partial xpath • Part of absolute xpath, locates a unique element • Identify web element Username on gmail.com • //input[@value='Next'] • Identify web element Next button on gmail.com • //input[@value='Next'] 5/5/2021 Selenium Webdriver 2.0 61
  • 62. More example on Xpaths • Identify link “Need Help” on gmail.com • //*[@id='gaia_firstform']/div/a • and condition • //input[@id=‘Email’ and name=‘Email’] - gmail.com • Or condition • Functions • Contains, starts-with • //*[starts-with(@id,’yui_3_4’)]/ul/li[1] – yahoo.com autosuggestion 5/5/2021 Selenium Webdriver 2.0 62
  • 63. cssSelector • CSS stands for Cascading Style Sheets • CSS defines how HTML elements are to be displayed • Are comparatively has fast performance especially in IE and Chrome browser • Syntax - *[id=‘id value’] • *[id=‘Email’] – gmail.com • input[id=‘Email’] - gmail.com • Example • Driver.findElement(By.cssSelector(“input[id=‘Email’]”)).sendKeys(“AAAA”); • input[id=‘Email’][name=‘Email’] - gmail.com • div[class=‘product –info mail’] p – gmail.com • #passwd – same as id=passwd in gmail.com • Example • driver.findElement(by.cssSelctor(“#passwd”)).sendKeys(“AAA”); • More explanation in Notes section 5/5/2021 Selenium Webdriver 2.0 63
  • 64. cssSelector • Input[name^=‘Ema’] – find element whose name starts with Ema • Input[name$=‘ail’] – find element whose name ends with ail • Input[id*=‘ai’] – find element whose name contains with ai 5/5/2021 Selenium Webdriver 2.0 64
  • 65. cssSelector • //input[starts- with(@id,’yui_3_4_0_1_136255’)/ul/li[1]/a – yahoo.com search field • Example • Driver.get(http://yahoo.com”); • Driver.findElement(By.xpath(“//input[@id=‘p_13838465- p’]”))/sendKeys(“Hello”); • Thread.sleep(4000L); • String text = driver.findElement(By.xpath(“//*[starts- with[@id,’yui_3_4_0_1_136255’)/ul/li[1]/a]) • System.out.println(text); 5/5/2021 Selenium Webdriver 2.0 65
  • 66. Exercise • Read properties file • Browser=chrome • Based on browser key open browser • Open gmail.com • Enter user and password • Login to gmail.com 5/5/2021 Selenium Webdriver 2.0 66
  • 67. GUI Controls • GUI Controls/web Elements on Webpage and its operations 5/5/2021 Selenium Webdriver 2.0 67 Control Operations Input Input value, read value, clear value Label Read text Drop Down List Select Single element, Read All elements, Clear value, find total no of elements Link Click, getText of a link Radio Button Select and Toggle Check Box Select and toggle Image Read image Button Click, getText on button
  • 68. Selenium – GUI Controls • Working with Firefox, IE, Chrome, HTMLUnitDriver • GUI Controls • Input • Button • Links • Extracting all links on a webpage • Extracting objects from a specific area of a webpage • Finding if object is present or not • Dropdown list • Checkbox • Radio Button • Finding if object is hidden or displayed on web page • How to take screenshot? • Implicit and explicit wait • PageLoadTimeout • webDriverWaitclass • webDriver Timeout • ExpectedCondition interface and ExpectedConditions class • WaitUntil Condition • Fluent wait • Managing Ajax based component 5/5/2021 Selenium Webdriver 2.0 68
  • 69. Challenges • Identification of web element • Dropdown list, Button,Image,Text,Input • Object xpath may be dynamic in nature (Every run it changes) • Reopen website and check xpath • Object is not visible • Check isDisplayed property • Object is in frame • Check xpath window and see left hand side displays frame or right click object and check if it is on frame • Automation Environment unavailability • Application stability • Features, workflows being changed frequently leading to maintenance issues • Test data is changed frequently and needs regular modification and maintenance • Object and their properties are changes frequently • Unreal expectation from project manager/test manager, if they expect automation to happen at the click of a button • Automation tool support to automate all feature of the application • Managing test results for every build for future reference 5/5/2021 Selenium Webdriver 2.0 69
  • 70. HTML Tags • Web Element – tag, mandatory and optional HTML tags 5/5/2021 Selenium Webdriver 2.0 70
  • 71. GUI Controls • Input • Sendkeys • getAttribute(“attributeName”) • Generally input HTML tag will have VALUE aatribute – indicate the value of the input field • Other attributes are -- id, class, type (text), name • Driver.findElement(By.xpath(“xpath”)).getAttribute( “attributeName”); • How to input value inside input field? • sendKeys(“actual value to type”) • clear(); 5/5/2021 Selenium Webdriver 2.0 71
  • 72. GUI Controls(Button) • Button • How to get text written on a button? • Driver.findElement(By.xpath(“xpath”)).getAttribute(“value”); • Driver.findElement(By.xpath(“xpath”)).getText(); • How to click on a button? • Driver.findElement(By.xpath(“xpath”)).click(); 5/5/2021 Selenium Webdriver 2.0 72
  • 73. GUI Controls(Link) • Links • To click on a specific link : click() • driver.findElement(By.xpath(“xpath”)).click(); • Get Text of a link : getAttribute(“value”); • driver.findElement(By.xpath(“xpath”)).getAttribute(“value”); • How to get a link using text written on it instead of xpath? • driver.findElement(By.linkText(“linktext”).click(); • driver.findElement(By.partiallinkText(“linktext”).click(); 5/5/2021 Selenium Webdriver 2.0 73
  • 74. GUI Controls(Link) WebDriver driver = new FirefoxDriver(); driver.get(“http://bbc.com”); List<WebElement> allLinks = driver.findElements(By.tagName(“a”)); System.out.println(“Total Links : “ + allLinks.size()); // print ALL link’s text for(int i=0;i<allLinks.size();i++) System.out.println(allLinks.get(i).getText()); • Few links do not have text • Few Links are hidden – allLinks.get(i).isDisplayed() // if true, text is visible to user 5/5/2021 Selenium Webdriver 2.0 74
  • 75. GUI Controls(Link) • How to find all input fields on facebook.com • List<WebElement> fields = driver.findElements(By.xpath(“//input[@type=‘text’ or @type=‘password’]”); • System.out.println(“Total input fields are : “ + fields.size()); • fields.get(0).sendKeys(“one”); • fields.get(0).sendKeys(“two”); • fields.get(0).sendKeys(“three”); • fields.get(0).sendKeys(“four”); • fields.get(0).sendKeys(“five”); • fields.get(0).sendKeys(“six”); • fields.get(0).sendKeys(“seven”); 5/5/2021 Selenium Webdriver 2.0 75
  • 76. GUI Controls(Link) • How to get links from specific area on a webpage? • Extract all links from the red box mentioned in below image. 5/5/2021 Selenium Webdriver 2.0 76
  • 77. GUI Controls(Link) • Procedure to get all links and click each click from red box • Get xpath of red box • Find all links using tagName locator for the identified xpath • Print links • Click on link (open a new link page) and move control back to original page • And loop for all links driver.get(“http://bbc.com”); WebElement box = driver.findElement(By.xpath(“xpath of a box”)); List<WebElement> links = driver.findElements(By.tagName(“a”)); System.out.prinln(“Total Links : “ + links.size()); for (int i=0;i<links.size();i++) { System.out.pringln(links.get(i).getText()); links.get(i).click(); System.out.prinln(driver.getTitle()); driver.get(http://bbc.com”); box = driver.findElement(By.xpath(“xpath of a box”)); links = driver.findElements(By.tagName(“a”)); System.out.ptintln(“New Link ……………”); } 5/5/2021 Selenium Webdriver 2.0 77
  • 78. GUI Controls(Link) • Another way to extract all links from red box (Creating dynamic xpaths) 5/5/2021 Selenium Webdriver 2.0 78
  • 79. GUI Controls(Link) • Drawback of above method is, if links are increased or decreased, code will not work as expected • How to overcome this problem? • Find out if link exist using function as below Public static boolean isElementPresent( String ElementXpath) { Int count = dirver.findElements(By.xpath(ElementXpath)).size(); If (count ==0) return false; else return true; } 5/5/2021 Selenium Webdriver 2.0 79
  • 80. GUI Controls(Link) String part1=“xpath1”; String part2=“xpath2”; int i=1; while(isElementPresent(part1+i+part2)) { String text = driver.findElement(By.xpath(part1+i+part2)).getText(); System.out.println(text); driver.findElement(By.xpath(part1+i+part2)).click(); System.out.println(driver.getTitle()); driver.get(http://bbc.com”); i++; } 5/5/2021 Selenium Webdriver 2.0 80
  • 81. GUI Controls(Dropdown) driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html"); driver.manage().window().maximize(); WebElement element = driver.findElement(By.xpath("//*[@id='Carlist']")); Select list = new Select(element); System.out.println("Is list multiSelect? : " + list.isMultiple()); //selects a element/item using visible text list.selectByVisibleText("Opel"); Thread.sleep(4000L); list.selectByIndex(3); Thread.sleep(4000L); list.selectByValue("Renault Car"); List<WebElement> low = list.getOptions(); System.out.println("total options : " + low.size()); for(int i=0;i<low.size();i++) System.out.println(low.get(i).getText()); • Exercise • Next dropdown list operation 5/5/2021 Selenium Webdriver 2.0 81
  • 82. GUI Controls(Dropdown) • How to find all elements present in dropdown list? WebElement droplist = driver.findelement(By.xpath(“xpath”)); List<WebElement> allOptions =droplist.findElements(by.tagName(“option”)); System.out.println(“Total Elements present:” + allOptions.size()); //print all elements for(int i=0;i<allOptions.size();i++) System.out.println(allOptions.get(i).getText()) + “ – “ + allOptions.get(i).getAttribute(“selected”); 5/5/2021 Selenium Webdriver 2.0 82
  • 83. GUI Controls(Dropdown) • Dowpdown list using Select class WebElement element = driver.findElement(By.xpath("//*[@id='Carlist']")); Select list = new Select(element); System.out.println("Is list multiSelect? : " + list.isMultiple()); //selects a element/item using visible text list.selectByVisibleText("Opel"); Thread.sleep(4000L); list.selectByIndex(3); Thread.sleep(4000L); list.selectByValue("Renault Car"); List<WebElement> low = list.getOptions(); System.out.println("total options : " + low.size()); for(int i=0;i<low.size();i++) System.out.println(low.get(i).getText()); 5/5/2021 Selenium Webdriver 2.0 83
  • 84. GUI Controls(Radio Button) • Radio Button • Can select one radio button from a group of radio buttons • Radio Button either be selected or unselected. • Html Tag - input • Has name – group name • Value – display text • Type – radio 5/5/2021 Selenium Webdriver 2.0 84
  • 85. GUI Controls(Radio Button) • www.echoecho.com/htmlforms10.htm 5/5/2021 Selenium Webdriver 2.0 85
  • 86. GUI Controls(Radio Button) • driver.get(http://www.echoecho.com/htmlforms10.htm”); • List<WebElement> radios=driver.findElements(By.xpath(“//input[@name=‘grou p1’]”)); • System.out.println(“Total Radio Buttons : “ + radios.size()); • System.out.println(radios.get(0).getAttribute(“checked”)); • System.out.println(radios.get(1).getAttribute(“checked”)); • System.out.println(radios.get(2).getAttribute(“checked”)); • // click on 0th radio button milk • radios.get(0).click(); • System.out.println(radios.get(0).getAttribute(“checked”)); • System.out.println(radios.get(1).getAttribute(“checked”)); • System.out.println(radios.get(2).getAttribute(“checked”)); 5/5/2021 Selenium Webdriver 2.0 86
  • 87. Exercise • Exercise • Link • Get text and click on “Can’t Access to you account” on Yahoomail.com • Radio Button • After clicking on “Can’t Access to you account” link, get radio buttons from next page 5/5/2021 Selenium Webdriver 2.0 87
  • 88. End of Day - 1 5/5/2021 Selenium Webdriver 2.0 88
  • 89. Junit framework • What is Junit? • Configuring Junit in Selenium • Junit Annotations • Running Test in Junit • Skipping a test • Parameterizing Tests • Assertion • Reporting an Error • Batch Runner • What is ANT – Build and Compile tool • Downloading and configuring ANT • Build.xml • HTML report using ANT • Building a BAT file to run tests using ANT 5/5/2021 Selenium Webdriver 2.0 89
  • 90. TestNG Framework • What is TestNG? • Installing TestNG • TestNG annotations • Running Test in TestNG • Batch running in TestNG • Skipping Test • Parameterization – DataProvider • Assertion, Reporting errors • TestNG Reports • Advantages over jUnit • Grouping tests • Priority of execution • DataProviders for multiple tests in single file • Single dataprovider for multiple test cases • Listeners for logging passed, failed, skipped test case • TestListenerAdapter 5/5/2021 Selenium Webdriver 2.0 90
  • 91. Junit Framework • Junit is a test framework for unit testing/Functional testing • Junit is integrated with Selenium • Junit is a controlling entity which controls test cases 5/5/2021 Selenium Webdriver 2.0 91
  • 92. Junit Framework contd… • Configure Junit library with project • Configure Build path • Annotations • @Test : Signifies this is a test case • @Ignore : Skips the test case • @Before: Called before EACH test case having @Test annotation • OpenBrowser • @After : Called after each test case having @Test annotation • CloseBrowser • @BeforeClass: Executed before executed a class (once for class). This method has to be static. • Open database connection • @AfterClass : Executed before executed a class (once for class). This method has to be static. • Close database connection • Physical position does not matter. • Test Suite: is nothing but collection of test cases • Run suite containing 2 test cases as below • Create tests package and Mysuite.java file containing below 2 annotations to run firsttestcase and secondtestcase • Firsttestcase.java contains • 2 Test method with @Test annotations • Firsttestcase.java contains • 3 Test methods with @Test annotations1 • Mysuite.java contains • @RunWith(Suite.class) • @SuiteClasses({firsttestcase.class,secondtestcase.class}) // test cases from firstclass and then test cases from secondclass will be executed. • And run Mysuite.java as Junit test case 5/5/2021 Selenium Webdriver 2.0 92
  • 93. Junit Framework contd… • How to decide order of execution? • @FixMethodOrder(MethodSorters.NAME_ASCEN DING) • Have test case name as aa_, ab_, ac_ • Bad practice – Test cases has to be independent of each other. 5/5/2021 Selenium Webdriver 2.0 93
  • 94. Junit Framework contd… • Can have as many Test methods as you can. • Run Junit test script as Junit test and not Java application • Create build.xml (copy) • Create report folder under project folder and specify in test.reportsDir • HTML based reports • Need to run Junit tests with ANT (Build and compile tool) 5/5/2021 Selenium Webdriver 2.0 94
  • 95. Junit Framework contd… • To skip all @Test inside a particular class, use • Assume.assumeTrue(false) inside @BeforeClass annotation OR • Remove class name from @SuiteClasses annotation from Mysuite.java • Assertions • To verify a condition and report result into Junit framework • Assert.assertTrue(expectedResult,actualResult); • Drawback: Once Assertion is failed, test script execution halts. • To avoid, use try-catch block. • Assert.AssertTrue(“Error Message”,4>3): If condition fails, error message is executed. • But Junit output assume that test cases is passed • @Rule • Public ErrorCollector errcol = new ErrorCollector(); • In catch block write errcol.addError(t); • Try {Assert.AssertTrue(“Error Message”,4>3}catch(Throwable t){errcol.addError(t); } 5/5/2021 Selenium Webdriver 2.0 95
  • 96. Junit Framework contd… • Parametrization // first step – define annotation @RunWith(Parameterized.class) public class ParameterTestCase(){ public String username; public String password; public int pincode; // second step – create constructor public ParametertestCase(String username, String password, int pincode) { this.username=username; this.password=password; this.pincode=pincode; } //third step @Parameters public static void Collection<Object>[]> getData() { // row 1 Object[][] data = new Object[2][3]; // will executed for 2 rows Data[0][0]=“user1”; // first iteration uesrname Data[0][1]=“pwd1”; // first iteration password Data[0][2]=“234123”; // first iteration pincode //row 2 Data[0][0]=“user1”; // second iteration username Data[0][1]=“pwd1”; // second iteration password Data[0][2]=“234123”; // second iteration pincode Return Arrays.asList(data); // returns object array as ArrayList } 5/5/2021 Selenium Webdriver 2.0 96
  • 97. Junit Framework contd… • Collection is a interface • Collection a= new ArrayList(); • a.add(“Pune”); • a.add(“Mumbai”); • a.add(“Delhi”); • Arrays.asList(data) : Converts Object array into arraylist 5/5/2021 Selenium Webdriver 2.0 97
  • 98. Junit Framework contd… @Test public void testRegister() { System.out.println(“Registering User : “ + username + “ – “ + password + “ -- “ + pincode); } 5/5/2021 Selenium Webdriver 2.0 98
  • 99. ANT – Build & Compile Tool • Ant is used to prepare HTML reports for test cases executed • ANT is available on Windows and Unix/Linux • ANT is a Build, Compile and Deploy tool • Download ANT • http://ant.apache.org/bindownload.cgi • Unzip the extracted file • Copy extracted path and set environment variables • ANT_HOME=copied path • PATH=append ; and paste pathbin • Go to command prompt and issue command • Ant and press ENTER • If no error appears ANT is successfully installed. • Build.xml is a heart of ANT 5/5/2021 Selenium Webdriver 2.0 99
  • 100. ANT – Build & Compile Tool Contd… • Create build.xml under project folder as below ws.home: project folder ${basedir} Ws.jars: where all jar files are present – Selenium, poi, log4j etc. D:jars Test.dest: project class file stored here after compilation of project ${ws.home}/build Test.src: ${ws.home}/src Where all .JAVA files are present Test.reprotdir:C:rep Create this subfolder before running ANT. All reports will be stored here. 5/5/2021 Selenium Webdriver 2.0 100
  • 101. ANT – Build & Compile Tool Contd… • Targets Clean: Deletes target folder Compile : deletes target folder, create again, and compile java files, creates .class files under build folder as mentioned in build.xml Run: Compile java files and run add <include name=packagename/testcasename1.class/> <include name=packagename/testcasename2.class/> <include name=packagename/testcasename3.class/> • Go to Command prompt and go to project folder > ant clean > ant compile : creates build folder and creates class files for all java files  ant run  Go to c:rep which was given in build.xml for test.reportsDir and click on index.htmls to open HTML reports 5/5/2021 Selenium Webdriver 2.0 101
  • 102. ANT – Build & Compile Tool & Batch File Creation Contd… • To run all class file created by ANT compile target use below statement in build.xml • <include name=**/*.class/> instead of mentioning class file names. • One can run Runner class MyTestSuiteRunner.class using • <include name=packagename/MyTestSuiteRunner.class/> Will execute all test cases (test suite) mentioned in MyTestSuiteRunner.class • How to Create batch file? • Create a blank notepad file and type cd Cd <project path> ant clean compile run And save this file as “filename.bat” • Double click this .bat file to execute all test cases. That’s all !!!! 5/5/2021 Selenium Webdriver 2.0 102
  • 103. ANT – Build & Compile Tool & XSLTreprots • How to create XSLReports • Create a folder under src/xslt • Copy this file into it • Download these 2 Saxon8.7.jar and saxonLiaison.jar files. - https://github.com/prashanth-sams/testng- xslt-1.1.2/tree/master/lib • Run ant makexsltreports • Open <projectpath>XSLT_Reportsoutputindex.html to see xsltreports 5/5/2021 Selenium Webdriver 2.0 103
  • 104. TestNG Framework • TestNG is most famous test framework now a days • Many features over Junit Java framework • Parallel test execution, GRID integration, Flashy xml reports with graph 5/5/2021 Selenium Webdriver 2.0 104
  • 105. TestNG Framework Contd… • Google “Install TestNG” click on first link (Current release) • Eclipse should be above 3.4 • Copy link next to 3.4 or above in Install Software in Eclipse • Go on clicking and finish the installation. • Verify if TestNG is installed as a plugin • Windows->View->Other->Java->TestNG 5/5/2021 Selenium Webdriver 2.0 105
  • 106. TestNG Framework Contd… • Configure project with TestNG library and selenium jar files. • Test NG Annotations • Has predefined order of execution. Method can have any name for all annotations. • @Test: This is a test case • @BeforeMethod: Executes with every @test annotation • Used to open browser • @BeforeTest: Executes first before executing any of the test. Executed only once in the execution. • Used to connect to database. • @AfterMethod: Executes with every @test annotation after @Test annotation is execute. • Used to close browser • @AfterTest: Executes first after executing any of the test. Executed only once in the execution. • Used to shutdown/close to database. • @BeforeSuite: Executed before executing a test suite (Test suite is a collection of test cases) This annotation can be present in one of the test script (across multiple java files) if there are multiple suites. • Initialize or create webdriver interface. • @AfterSuite: This annotation can be present in one of the test script if there are multiple suites. • Any no of @Test annotations can be created • When run, any test case can run first, there is not predefined order for running test cases. Priority defines execution order. • Test-output folder is created • Index.html is created where HTML report is created automatically. • Run as a TestNG test • You can see HTML report in test-output folder. • Observe 5/5/2021 Selenium Webdriver 2.0 106
  • 107. TestNG Framework Contd… • To run multiple java files using TestNG, testng.xml is required and should be under project folder. • 2 Class files under testPkg package • Single test can be skipped by mentioning skip new … inside test annotation. • Check report to see passed, failed and skipped result 5/5/2021 Selenium Webdriver 2.0 107
  • 108. TestNG Framework Contd… • Skipping a test case • In @BeforeTest annotation use • throw new SkipException(“Skipping a test case”); • Parameterization • Running a single test with multiple set of data • Logging in to Gmail.com • DataSets are • Valid user, valid password • Valid username, invalid password • Invalid username, valid password • Invalid username, invalid password 5/5/2021 Selenium Webdriver 2.0 108
  • 109. TestNG Framework Contd… • @DataProvider Public Object[][] getData() { Object[][] data = new Object[4][2]; // test will be repeated for 4 times, 2 are the no of columns //row1 Data[0][0]=“valid user”; Data[0][1]=“valid password”; //row2 Data[1][0]=“valid user”; Data[01[1]=“invalid password”; // row3 Data[2][0]=“invalid user”; Data[2][1]=“valid password”; //row4 Data[3][0]=“invalid user”; Data[3][1]=“invalid password”; Return data; } 5/5/2021 Selenium Webdriver 2.0 109
  • 110. TestNG Framework Contd… • @Test(dataPriovider=“getData”) • Public void Login(String username, String password) • { • System.out.println(username + “ – “ + password); • } • Run above test using testng.xml 5/5/2021 Selenium Webdriver 2.0 110
  • 111. TestNG Framework Contd… • Assertions • To check if a specific condition is satisfied or not • Example: Link is present, specific text is present • Assert.assertEquals(expectedResult,ActualResult); • Assert.assertEquals(x,y); • If value of x <> value of y then fail the test case else pass. • Check the HTML report for result • Assert.assertTrue(message,condition); • Assert.assertTrue(“Error message”,6>1); • If condition evaluates to true, test will pass else fail. • Assert.assertFalse(message,condition); • If condition evaluates to false, test will pass else fail. 5/5/2021 Selenium Webdriver 2.0 111
  • 112. TestNG Framework Contd… • Statements after assertion statement is not executed when assertion is failed and control goes to next test case. • IF you want to continue even when assertion fails(for minor error), use try catch block. (with throwable – Error and Exception). When assertion fails, control moes to catch block and TestNG reports test case as passed and not failed. 5/5/2021 Selenium Webdriver 2.0 112
  • 113. TestNG Framework Contd… • Build.xml changes • Target “run” should have below statement • <xmlsfileset dir=“${ws.home}” includes=“testng.xml” • To run reports use command • ant makexlstreports • Where makexlstreports is a target like clean, compile, run • Below jar files are required and configure with project. (Download from <http://www.java2s.com/Code/Jar/s/Downloadsaxon87jar.htm>) • Create xslt package under project folder, create testng-results.xsl file. • Issue command ant clean compile run makexsltreports • Compile project if there are changes done in project code • Refresh project folder in Eclipse • XLST_Reports folder is created and xlst reports are generated • Test-output are primitive HTML reports 5/5/2021 Selenium Webdriver 2.0 113
  • 114. TestNG Framework Contd… • Order of test case execution will not be dependent on physical position. But it depends on priority. • Order of execution : testChangePwd,testLogout,testLogin • If testLogin test case fails other 2 test cases will be skipped. • @Test(priority=3,dependsOnMethods={“testLogin”}) • Public void testLogout(){ System.out.println(LogoutTest”); • @Test(priority=2,dependsOnMethods={“testLogin”}) • Public void testChangePwd(){ System.out.println(Password Change Test”); • @Test(priority=1) • Public void testLogin(){ System.out.println(LoginTest”); • // Assert.assertEquals(“A”,”B”); fails test case 5/5/2021 Selenium Webdriver 2.0 114
  • 115. TestNG Framework Contd… • Separate dataProviders with different names in single java file. Many test cases with many dataproviders but in single java file. • Data_Provider.java Public class Data_provider // dataprovider 1 { @DataProvider(name=“regTestDataProvider”) Public static Object[][] getData() { Object data[][]=new Object[2][3]; Data[0][0]=“U1”; Data[0][0]=“P1”; Data[0][0]=“xyz@gmail.com”; Data[1][0]=“U2”; Data[1][1]=“P2”; Data[1][2]=abc@gmail.com”; Return data;} } Public class Data_provider // dataprovider 2 {@DataProvider(name=“loginTestDataProvider”) Public static ?Object[][] getLoginData() {Object data[][]=new Object[2][3]; Data[0][0]=“U1”; Data[0][0]=“P1”; Data[1][0]=“U2”; Data[1][1]=“P2”; Return data;}} 5/5/2021 Selenium Webdriver 2.0 115
  • 116. TestNG Framework Contd… • Associate dataprovider with test case • Sample.java • Public class SampleTest{ • @Test(priority=1,dataProviderClass=Data_Provider.class,data Provider=“loginTestDatAProvider”) • Public void testLogin(String username, String password){ • System.out.println(“Login Test ” + username + “ – “ + password); } • @Test(priority=2,dataProviderClass=Data_Provider.class,data Provider=“regTestDataProvider”) • Public void testReg(String username, String password, String email){ • System.out.println(“Login Test ” + username + “ – “ + password + “ – “ + email); } 5/5/2021 Selenium Webdriver 2.0 116
  • 117. TestNG Framework - ANT Contd… • XSLT stands for XML (Extensible Markup Language) Stylesheet Language for Transformations. XSLT gives interactive(user friendly) reports with "Pie Chart"; but only on TestNG framework. • Create folder srcxslt • Create testng-results.xls file (copy) • Create build.xml and update it • Go to project folder • ant clean compile run • An makexsltreports • Create a BATCH file • cd • F:rishikeshSeedInfoTechTestNG • Ant clean compile run makexsltreports 5/5/2021 Selenium Webdriver 2.0 117
  • 118. Reading a properties file • .properties • Name=“Tom” • Age=23 • City=Pune • #Hobbies=Cricket,Football • Browser=Firefox • testsiteURL=http://gmail.com • Comments are indicated by# • Properties prop = new Properties(); • FileInputStream fs = new FileInputStream(“D:temptemp.properties”); • Prop.load(fs); • System.out.println(prop.getProperty(“name”)); • System.getProperty(“user.dir”) – returns project folder 5/5/2021 Selenium Webdriver 2.0 118
  • 119. POI Library – Accessing Excel Files • POI Library by Apache • Used to access Excel file • Very rich library containing all methods to read/write/delete/update workbooks, sheets, cells • Download and configure below 5 Jar files to work with Excelfiles 5/5/2021 Selenium Webdriver 2.0 119
  • 120. POI Library – Accessing Excel Files contd... • Create Excel file data.xls on D:temp in sheet ‘details’ Name Age City Ankit 21 Pune Amruta 20 Mumbai Shailesh 23 Nagpur Ramita 21 Delhi Xls_Reader xls = new Xls_Reader(“D:tempdata.xls”); int totRow = Xls.getRowCount(“details”); int totCol = Xls.getColCount(“details”); String Data = xls.getCellData(“details”,”Name”,3); xls.SetCellData(“details”,”Name”,6,”Asin”); 5/5/2021 Selenium Webdriver 2.0 120
  • 121. Logging Data • Allows to write logs/errors/debug messages into log file • Create or copy log4j.proeprties into project folder (src) • Download log4j API and configure in project • Log4j API reads log4j.proeprties • import org.apache.log4j.Logger; • Create Logger object ponting to devpinoyLogger • Log4j.properties contents. • 5/5/2021 Selenium Webdriver 2.0 121
  • 122. Logging Data contd… • Logger ApplLogs = Logger.getLogger(“devpinoyLogger”); • ApplLogs.debug(“Logging started….”); • ApplLogs.debug(“Logging in progress….”); • ApplLogs.debug(“Logging ending….”); 5/5/2021 Selenium Webdriver 2.0 122
  • 123. Working with Different Browsers • How to use Firefox browser? • WebDriverdriver = new FirefoxDriver(); • How to use Chrome browser? • System.setProperty(“webdriver.chrome.driver”,”path of chromedriver”); • WebDriverdriver = new ChromeDriver(); • How to use IE browser? • System.setProperty(“webdriver.ie.driver”,”path of IE driver”); • WebDriverdriver = new InternetExplorerDriver(); 5/5/2021 Selenium Webdriver 2.0 123
  • 124. Screenshot • How to take screenshot when error occurs? • // get screenshot in binary form • File scrFile=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); • // convert into jpg format to specified destination • FileUtils.copyFile(scrFile,new File(“F:RishikeshSeedInfoTechScreenshotsgmail.j pg”)); • FileName – Generate unique file name using date and time 5/5/2021 Selenium Webdriver 2.0 124
  • 125. Screenshot Calendar cal = new GregorianCalendar(); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); int sec = cal.get(Calendar.SECOND); int minute = cal.get(Calendar.MINUTE); int hour = cal.get(Calendar.HOUR); int date = cal.get(Calendar.DATE); int day = cal.get(Calendar.HOUR_OF_DAY); DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Date date1 = new Date(); //get current date time with Date() String date2= dateFormat.format(date1); System.out.println(date2); // Print the Date System.out.println("month : " + month); System.out.println("year : " + year); System.out.println("sec : " + sec); System.out.println("minute : " + minute); System.out.println("hour : " + hour); System.out.println("date : " + date); System.out.println("day : " + day); fileName = year+"_"+date+"_"+(month+1)+"_"+day+"_"+minute+"_"+sec+".jpg"; // convert into jpg format to specified destination FileUtils.copyFile(scrFile,new File("F:RishikeshSeeedInfoTechScreenShotsgmail" + fileName +".jpg")); 5/5/2021 Selenium Webdriver 2.0 125
  • 126. Exercises • Go to Dice.com search selenium jobs • Click on each page link 1,2,3,4,5 • Go to google.com • Search for mobile phone • Print all links on the first page 5/5/2021 Selenium Webdriver 2.0 126
  • 127. Waits • Implicit and Explicit wait • PageLoadTimeout • WebDriverWait Class • Expectedcondition class • WaitUntil Condition • Fluent Wait • Managing Ajax based components • Yahoo.com • Google.com • Window Handles 5/5/2021 Selenium Webdriver 2.0 127
  • 128. Implicit Wait • Implicit wait – Global timeout • driver.manage().timeouts().implicitlywait(10,TimeU nits.SECONDS); • findElements waits for 10 Second maximum before it finds an element. • This setting is applicable to complete test script 5/5/2021 Selenium Webdriver 2.0 128
  • 129. Explicit Wait • Is not a global wait • Its specific to an element • Waits for specific condition is true/met • Two types of classes used (implements wait interface) 1. WebDriverWait 2. FluentWait 5/5/2021 Selenium Webdriver 2.0 129
  • 130. Explicit Wait • Hdfc.com • webDriverWait wait = new webDriverWait(driver,20); // Selenium polls with every microsecond if the element is found • wait.until(ExpectedConditions.visibilityOfElementLo cated(By.xpath(“xpath”)) • wait.until(ExpectedConditions.invisibilityOfElement Located(By.xpath(“xpath”)) 5/5/2021 Selenium Webdriver 2.0 130
  • 131. FluentWait • Wait for a specific element is found • FluentWait<WebDriver> fwait = new FluentWait<WebDriver>(driver) • .withTimeout(30,TimeUnits.SECONDS) • .pollingEvery(5,TimeOuts.SECONDS) • .ignoring(NoSuchElementException.class); • Explanation • Waits for 30 seconds • Polls every 5 seconds • Ignores NoSuchElementException exception • Example • fwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpat h(“xpath”))); • s 5/5/2021 Selenium Webdriver 2.0 131
  • 132. Wait- PageLoadTimeout • driver.manage().timeouts().pageLoadtimeout(30,Ti meUnits.SECONDS); • If new page is not loaded in specified SECONDS, selenium will throw exception. 5/5/2021 Selenium Webdriver 2.0 132
  • 133. Alerts Alert al = driver.switchTo.alert(); System.out.println(al.getText()); Al.accept(); // or Al.dismiss() // switch to main window back driver.switchTo().defaultContent(); 5/5/2021 Selenium Webdriver 2.0 133
  • 134. Window Handling • Each window has unique window id WebDriver driver = new FirefoxDriver(); Set<String> windIds = driver.getWindowHandles(); // ordered set System.out.println(“Total windows opened : “ + windIds.size()); // 1 window Iterator<String> it = windIds.iterator(); System.out.println(it.next()); driver.get(http://in.rediff.com”); // opens popups along with in.rediff.com webpage windIds = driver.getWindowHandles(); System.out.println(“total windows opened : “ + windIds.size()); // 2 windows it = windIds.iterator(); // again initialize iterator String mainWindow = it.next(); String popupWindow = it.next(); System.out.println(mainWindow); // unique window id System.out.println(popupWindow ); Exercise: http://timesofindia.indiatimes.com/ Click on Facebook icon 5/5/2021 Selenium Webdriver 2.0 134
  • 135. Window Handling – Another example WebDriver dr = new FirefoxDriver(); dr.get("https://www.salesforce.com/in/form/semfy16/crm- demo_b.jsp?d=70130000000t1oD&DCMP=KNC- Google&mkwid=6YuZhCqn&pcrid=70285087026&type=Exact&pdv=c"); dr.findElement(By.xpath("//*[@id='form-container']/div[3]/div/a[2]")).click(); Set<String> windIds = dr.getWindowHandles(); System.out.println("total windows opened : " + windIds.size()); Iterator<String> it = windIds.iterator(); String mainWindow = it.next(); String childWindow = it.next(); dr.switchTo().window(childWindow); Thread.sleep(5000L); System.out.println(dr.findElement(By.xpath("//*[@id='content']/div[1]/div/h1")).getText()); Thread.sleep(3000L); dr.switchTo().window(mainWindow); System.out.println(dr.findElement(By.xpath("//*[@id='layout']/div[1]/div[1]/div/div/div/div[2]/div/div /h2")).getText()); Exercise: http://timesofindia.indiatimes.com/ Click on Facebook icon 5/5/2021 Selenium Webdriver 2.0 135
  • 136. Frame Handling • Elements on frame are not accessible unless the focus is moved to frame WebDriver dr = new FirefoxDriver(); dr.get("http://www.firstcry.com/"); dr.findElement(By.xpath("html/body/div[5]/div[1]/div/div[2]/span[5]")).click(); int sz = dr.findElements(By.tagName("iframe")).size(); System.out.println("Total frames on page are " + sz); int cnt = 0; int i=0; int flag = 0; for(i=0;i<sz;i++) { dr.switchTo().frame(i); cnt = dr.findElements(By.xpath("//*[@id='Email']")).size(); if (cnt !=0) { flag = 1; dr.findElement(By.xpath("//*[@id='Email']")).sendKeys("AAAAA"); break; } dr.switchTo().defaultContent(); } if (flag == 1) {System.out.println("Element contains in frame : " + i);} else System.out.println("Element does not contain in any frame"); } 5/5/2021 Selenium Webdriver 2.0 136
  • 137. Frame Handling Another Example WebDriver dr = new FirefoxDriver(); dr.get("http://www.w3schools.com/html/tryit.asp?filename =tryhtml_iframe_height_width"); int totFrames = dr.findElements(By.tagName("iframe")).size(); System.out.println("Total frames on main page : " + totFrames ); dr.switchTo().frame(0); dr.switchTo().frame(0); System.out.println(dr.findElement(By.xpath("html/body/h1 ")).getText()); 5/5/2021 Selenium Webdriver 2.0 137
  • 138. Browser - Forward-Backward WebDriver dr = new FirefoxDriver(); dr.navigate().to("http://hdfc.com/"); dr.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); dr.manage().window().maximize(); dr.findElement(By.xpath("//*[@id='node- 18']/div/div/div/div/div[2]/nav/ul/li[2]/a")).click(); Thread.sleep(5000L); dr.navigate().back(); Thread.sleep(5000L); dr.navigate().forward(); 5/5/2021 Selenium Webdriver 2.0 138
  • 139. Actions class – Mouse Movement • Mouse deals with element which is not visible ut can be visible by moving mouse over it. • If element is not visible, selenium will not click on it • Write a program to click on GlofMenu->Woods->Driver – Should not work • Make element visible in order to click • Example • Clicking on GlofClubs->Woods->Driver WebDriver dr = new FirefoxDriver(); dr.get("http://www.americangolf.co.uk/"); Actions act = new Actions(dr); WebElement mainMenu = dr.findElement(By.xpath("//*[@id='navigation']/nav/ul/li[1]/a")); Thread.sleep(3000L); act.moveToElement(mainMenu).build().perform(); Thread.sleep(2000L); System.out.println("Moved to Gold Clubs menu"); WebElement driverMenu = dr.findElement(By.xpath("//*[@id='CLUBS_1']/div[1]/ul[2]/li/ul/li[2]/ul/li[1]/a")); Thread.sleep(3000L); act.click(driverMenu).build().perform(); System.out.println("Moved to Woods->Driver menu") Exercise • Print all links within Golf club main menu • Code in Notes section • Move price slider using Mouse class. • Code in Notes section 5/5/2021 Selenium Webdriver 2.0 139
  • 140. Miscellaneous • How to generate random number? Random r = new Random(); Int x = r.nextInt(100); // print no from 0 to 99 System.out.println(x); • Drag & drop – Price Slider Driver.get(http://www.americangolf.co.uk/golf- clubs/drivers?pmax=230&prefn1=brand&pmin=175&prefv1=CobraGolf); Actions act = new Actions(driver); WebElement point = driver.findElement(By.xapth(“xpath”)); act.dragAndDropBy(point,-100,0).build.perform(); • System.getProperty(“user.dir”) – Returns current project folder • driver.getTitle() – Returns current window title • driver.quit – closes all related windows • driver.close – closes current window • dr.manage().window().maximize() – maximizes current window 5/5/2021 Selenium Webdriver 2.0 140
  • 141. WebTable • Table on webpage is called web table. • Web table has rows and columns • HTML table structure • HTML tag – table • tr - table row • td – table data/cell • http://www.w3schools.com/html/html_tables.asp 5/5/2021 Selenium Webdriver 2.0 141
  • 142. WebTable • Xpaths to identify complete row, col and cell value/s • 4th row and 2nd column value • //table[@class=‘reference’]/tbody/tr[4]/td[2] • Complete First row • //table[@class=‘reference’]/tbody/tr[1] • Complete First row • //table[@class=‘reference’]/tbody/tr[1]/td • Column 2 • //table[@class=‘reference’]/tbody/tr/td[2] • All cells of a table • //table[@class=‘reference’]/tbody/tr/td 5/5/2021 Selenium Webdriver 2.0 142
  • 143. WebTable • Goto Rediff.com->Money • Print web table row by row driver.get(“”); List<WebElement> rows = driver.findElements(By.xpath(“table[@class=‘reference’]/tbody/tr”)); System.out.println(“total rows are : “ + rows.size()); for (int i=0;i<rows.size();i++) Systen.out.println(rows.get(i).getText()); • Print company name from first column of all rows /table[@class=‘reference’]/tbody/tr/td[1] 5/5/2021 Selenium Webdriver 2.0 143
  • 144. WebTable • Goto Rediff.com->Money • Print web table row by row driver.get(“”); List<WebElement> rows = driver.findElements(By.xpath(“table[@class=‘reference’]/tbody/tr”)); System.out.println(“total rows are : “ + rows.size()); for (int i=0;i<rows.size();i++) Systen.out.println(rows.get(i).getText()); • Print company name from first column of all rows /table[@class=‘reference’]/tbody/tr/td[1] 5/5/2021 Selenium Webdriver 2.0 144
  • 145. WebTable • Print price of a specific company String companyName=“Bata India”; List<WebElement> companyNames= driver.findElements(By.xpath(“/table[@class=‘reference’]/tbo dy/tr/tr[1] ”)); List<WebElement> currentPrices = driver.findElements(By.xpath(“/table[@class=‘reference’]/tbo dy/tr/tr[4]”)); For(int i=0;i<companyNames.size();i++) { If (companyNames.get(i).getText().equals(companyName)) Systen.out.println(companyNames.get(i).getText() + “ – “ + currentPrices.get(i).getText() ); } 5/5/2021 Selenium Webdriver 2.0 145
  • 146. WebTable • Print web table cell by cell List<WebElement> table= driver.findElements(By.xpath(“/table[@class=‘reference’]/tbo dy/tr/td”)); for(int i=0;i<table.size();i++) System.out.println(table.get(i).getText()); 5/5/2021 Selenium Webdriver 2.0 146
  • 147. End of Day - 2 5/5/2021 Selenium Webdriver 2.0 147
  • 149. Framework What is Framework? • A method or process with which one can • Maintain script • Log messages/errors • Create reports • Read data from various inputs like CVS file, Excel, database • Handle errors • Configure various environmental variables • Create faster test scripts • One time efforts • Junit and TestNG - Java Framework • DataDriven framework is a concept • Core framework – generic framework for any website Data Driven framework • Allows to drive test script with data from external input like database, CVS, Excel files. • Test scripts are not required to modify but only configuration file 5/5/2021 Selenium Webdriver 2.0 149
  • 150. Framework • Explain framework on board and then using test script • Each sheet contain data for single test case with sheet name = test case name • All data is stored in a single sheet • One sheet for test suite with suitename, runmode column • One sheet for TCID, comment, Runmode • One sheet for TCID, data1, data2, data3, runmode • Create Below Packages • Core • Main driver class to initialize Config, OR properties, define public variables – log, webdriver, database initialize • Load Excel file for data • Logs • Log4j properties helps to log errors/messages • Properties • Config.proerpties • Browser, TestSiteURL, ScreenshotPath • Objects.properties • xpaths • Testdata.xls • Sheets – TestSuite, LoginTest, registerUserTest • TestSuites – TCID, Desc, RunMode • LoginTest – username, password, positiveTest • RegisterUserTest - name, day, month, year, registerusername, password, repassword, email • Tests • LoginTest • RegisterUserTest • Utility • Common utility methods/functions – isElementPResent, click, type • Common Application methods/functions – login, logout, IsTestSuiteExecutable, isTestCaseExecuteble, isTestDataSetExecutable • XlsReader • Excel file for input data • Implementation using Junit framework • Create below folders • Screenshot • Build.xml – To run project using ANT build and compile tool • Application.log 5/5/2021 Selenium Webdriver 2.0 150
  • 151. Framework • LoginTest.java • Write constructor • Use Parameterization using Junit • RegisterUserTest • Write constructor • Use Parameterization using Junit • Show Run of framework (GUI) and show report 5/5/2021 Selenium Webdriver 2.0 151
  • 152. Framework • Step by Step procedure to create data driven framework • Using TestNG and WebDriver • Create a project – WebDriverTestNGDataDrivenFramework • Create package • dd_core – initialize variables, database connection, reading properties file • dd_logs – to maintain application logs – user defined • dd_properties – To read properties config and OR properties • dd_tests – Write and maintain all test cases • Rough – for rough work • dd_util – common application and common application functions • Write a code to capture a screenshot • Create config.properties file under dd_properties package • Create object.properties file under dd_properties package for maintaining xpaths/locators for link, input, buttons etc. 5/5/2021 Selenium Webdriver 2.0 152
  • 153. Framework • config.properties • testsite=http:/twitter.com • browser=firefox • Copy below 3 files into dd_util • DbManager.java, MonitoringMail .javaand TectConfig.java • Create application.log and selenium.log under dd_logs package • Configure Jar files for • Selenium • Poi jar files • TestNG Library • Log4j jar file • Mail.jar • Create test Core class under dd_core package • Initializing properties, Loading excel files, Creating DB connection, generating logs, init webDriver • Copy IEdriver and chromedriver into util package • Create testdata.xlsx under dd_properties • Sheets – TestSuite, LoginTest, registerUserTest • TestSuites – TCID, Desc, RunMode • LoginTest – username, password, positiveTest • RegisterUserTest - name, day, month, year, registerusername, password, repassword, email • Enter data into all sheets as mentioned in Notes 5/5/2021 Selenium Webdriver 2.0 153
  • 154. Framework • Copy xls_reader.java under dd_util package • testCore class public static Properties config = new Properties(); public static Properties object = new Properties(); public static Xls_Reader excel = null; public static WebDriver driver = null; @BeforeSuite public static void init() { If (driver == null) { //loading config , object properties and excel file FileInputStream fis = new FileInputStream(System.getPRoperty(“user.dir” + “srcdd_propertiesconfig.properties”); config.load(fis); FileInputStream fis = new FileInputStream(System.getPRoperty(“user.dir” + “srcdd_propertiesOR.properties”); object.load(fis); excel = new Xls_Reader(System.getProperty(“user.dir”) + “srcdd_propertiestestdata.xlsx” ); // decide webdriver to open browser If (config.getProperty(“browser”) .equals== “firefox”) driver = new FirefoxDriver(); Else if (config.getProperty(“browser”) .equals== “chrome”) { System.getPRoperty(“webdriver.chrome.driver”,”chromedriver.exe”); //copy driver to project folder driver = new ChromeDriver(); } Else if (config.getProperty(“browser”) .equals== “ie”) { System.getPRoperty(“webdriver.ie.driver”,”ieDriverServer.exe”); //copy driver to project folder driver = new InternetExplorerDriver(); } }} driver.manage().timeouts.implicitlyWait(20,TimeUnit.SECONDS); driver.get(config.navigate(“testsite”)); } 5/5/2021 Selenium Webdriver 2.0 154
  • 155. Framework • @AfterSuite • public static void quitDriver() • {driver.quit(); • monitoringMail mail = new monitoringMail(); • mail.sendMail(TestConfig.server,TestConfig.from, TestConfig.to, TestConfig.subject, TestConfig.messageBody, TestConfig.attachmentPath, TestConfig.attachmentName); • } • Object.properties • #LoginTest • username=//*[@id='signin-email'] • password=//*[@id='signin-password'] • signin=//*[@id='front-container']/div[2]/div[2]/form/table/tbody/tr/td[2]/buttondd_tests • Create LoginTest.java in dd_tests • @Test • public class LoginTest extends testCore{ // to use webdriver variable, properties files • @BeforeTest • public void isSkip(){ • If (!TestUtil.isExecutable(“LoginTest”)) • Throw new skipException(“Skipping test case as the run mode is set to N”); • } • public void doLogin() • { • driver.findElement(By.xpath(object.getProperty(“username”))).sendKeys(“AAAAA”); • driver.findElement(By.xpath(object.getProperty(“password”))).sendKeys(“BBBBB”); • driver.findElement(By.xpath(object.getProperty(“signin”))).click(); • }} 5/5/2021 Selenium Webdriver 2.0 155
  • 156. Framework Update testdata.xlsx for tCid and Runmode columns with Tcide runmode LoginTest N Create TestUtil file under dd_utils public class TestUtil extends Testcore { public static boolean isExecutable() { System.out.println("Tot rows : " + excel.getRowCount("test_suite")); for(int r=2;r<=excel.getRowCount("test_suite");r++) { System.out.println("test : " + excel.getCellData("test_suite", "tcid", r)); if ( excel.getCellData("test_suite", "tcid", r).equals("LoginTest")) { System.out.println("inside tcid row..."); if (excel.getCellData("test_suite", "runmode", r) == "Y") return true; else return false; } else return false; } return true; } 5/5/2021 Selenium Webdriver 2.0 156
  • 157. Framework • Update LoginTest for • isSkip method – Modification is already done in LoginTest.java in prior slide. • Run the project now. • Pass tcid to isExecutable function and change isExecutable and replace “LoginTest” with “tcid” parameter. • Write one more test case called secondtest and mentioned it in testdata.xls as runmode set to N • Copy LoginTest method as secondtest • Create testng.xml under project folder as below 5/5/2021 Selenium Webdriver 2.0 157
  • 158. Framework • Pass username, password to doLogin method and have • @Test(dataProvider=“getdata”) • In the same file write Dataprovider as below • @DataProvider • public Object[][] getData() • { • String sheetName=“LoginTest”; • int rows = excel.getRowCount(sheetName); • int cols = excel.getColumnCount(sheetName); • Object data[][] = new Object[rows-1][cosl]; • for(int rowNum=2;rowNum<=rows;rowNum++) • {for (int colNum=0;colNum<cols;colNum++) • data[rowNum-2][colNum] = excel.getCellData(sheetName, colnum, rowNum); } • return data; • } 5/5/2021 Selenium Webdriver 2.0 158
  • 159. Framework • Run the framework (Ensure LoginTest sheet has data for login – username, password with 2 rows ) • For Every other test case whichever requires parameter, we will have getData() method copied in the test script. To avoid the duplicate code, write common function getData(String sheetName) in TestUtil package • @DataProvider • Public object[][] getData() • { • Return TestUtils.getData(“LoginTest”); • } 5/5/2021 Selenium Webdriver 2.0 159
  • 160. Framework • Write one more static method in TestUtils package • Public static Object[][] getData(String sheetName) • { • int rows = excel.getRowCount(sheetName); • int cols = excel.getColumnCount(sheetName); • Object data[][] = new Object[rows-1][cols]; • for(int rowNum=2;rowNum<=rows;rowNum++) • {for (int colNum=0;colNum<=cols;colNum++) • Data[rowNum-2][col] = excel.getCellData(sheetName, colNum, rowNum); } • return data; • } 5/5/2021 Selenium Webdriver 2.0 160
  • 161. Framework • Interpretation of TestNG output • Green – pass • Yellow – Skipped • Red – Failed • Application Logging • testCore.java • Public static Logger appl_logs = Logger.getLogger(“devpinoylogger”); • Import files from org.apache.log4j not from testng • log4j.proeprties file • Only change the log file path where log file is generated 5/5/2021 Selenium Webdriver 2.0 161
  • 162. Framework • Log4j.properties contents • In respective places add below statements • apps_logs.debug(“Loading config properties file”); • apps_logs.debug(“Loading OR properties file”); • apps_logs.debug(“Loading Excel properties file”); 5/5/2021 Selenium Webdriver 2.0 162
  • 163. Screenshot • TestUtils.java add one more method public static void captureScreenshot(String suffix){ Calendar cal = new GregorianCalendar(); int month = cal.get(Calendar.MONTH); // current month int year = cal.get(Calendar.YEAR); // current year int sec = cal.get(Calendar.SECOND); // current second int min = cal.get(Calendar.MINUTE); // current minute int date = cal.get(Calendar.DATE); int day= cal.get(Calendar.HOUR_OF_DAY); //create unique file name with current timestamp File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try{ String mailscreenshotpath =System.getProperty("user.dir")+"dd_logsscreenshots"+ suffix +year+"_"+date+"_"+(month+1)+"_"+day+"_"+min+"_"+sec+".jpg"; FileUtils.copyFile(scrFile,new File(mailscreenshotpath)); } catch(IOException e){e.printStackTrace();}} • TestUtils.captureScreenshot(); // wherever you want to capture screenshot especially when test script is failed. • Run the framework right clicking on testng.xml and check screenshot folder for screenshots. 5/5/2021 Selenium Webdriver 2.0 163
  • 164. Framework • Drawback of current data driven framework • If you have 10000 test cases, creating and maintaining 10K sheets will be difficult • To avoid this one can have all test case data in one sheet 5/5/2021 Selenium Webdriver 2.0 164
  • 165. Error Handling & Reporting Error in TestNG • How to report errors in TestNG report? • Change password xpath to wrong xpath and make changes as below and run testng.xml • Put all statements in try and catch block in loginTest test script and inside catch block • Catch (Throwable t) • { • TestUtils.capturescreenshot(); // captures screenshot in case of error • Assert.assertTrue(false, t.getMessage()); // report failure in TestNG report/console • } • If there is no data for a test case, in that case TestUtils.getdata() should be changed to accommodate below changes • int rows = excel.getRowCount(sheetName)-1; • If (rows <=0) • {Object data[][] = new Object[1][0]; • Return data;} • Whenever there is a failure in the test case – failure is reported in testNG report, and control moves on to the next test case. 5/5/2021 Selenium Webdriver 2.0 165
  • 166. Framework • Create xls package under project folder • Download and configure Testng-xslt-maven-plugin-test-0.0.jar and saxon jars are present. • http://software-testing-tutorials-automation.blogspot.in/2014/07/download-required-jar-files-for.html • Configure ANT and create build.xml (prior to src folder) • Change 1.5 to 1.8 under compile target • Before running using ant ensure project is run using testng.xml from Eclipse and check reports as well • Go to project folder (prior to src folder) • ant clean compile run • Ensure to have makexsltreports target in build.xml • Copy testng.xls (module21 Hybridframework) to srcxlst folder • Goto project folder on command prompt • ant clean compile run makexsltreports • Go to Eclipse and refresh folder and observe xlst_reports • Open index.html file to see xslt reports 5/5/2021 Selenium Webdriver 2.0 166
  • 168. Hybrid Driven Framework • Combination of Data and Keyword • Requires less programming • Big projects are using hybrid driven framework • Process of creating hybrid driven framework • Decide which Java framework to use – TestNG or JUnit • Create DriverApp/keywordApp • Define keyword – Heart of Hybrid framework • Typing a text, entering field value, click on a link • Create test data file • Create keyword file • Create report.java – will generate report for each test case • Create email code file for sending failed test case report • Integrate ANT 5/5/2021 Selenium Webdriver 2.0 168
  • 169. Hybrid Driven Framework 5/5/2021 Selenium Webdriver 2.0 169
  • 170. POM • POM – Page Object Model • Based on webpages • Example there are 10 pages, will create 10 java files • Based on encapsulation and inheritance • When to use POM? • When there are similar web pages • Example facebook.com everyone has a wall but with different content • Twitter.com • POM can be implemented using Junit or TestNG • School IS A institution -- inheritance • FirefoxDriver implments WebDriver interface • Public class School extends institution -> Schools class acquires all properties of institution. • { Room r = null; • Public School (Room r){this.r=r;} • School Has A room (class rooms) – Encapsulation • Test.java • Public class Room{ • Public int space; • Public void setSpace(){space=s;} • Public void getSpace(){System.out.println(s);} 5/5/2021 Selenium Webdriver 2.0 170
  • 171. POM • Its data driven model • Most happening framework now a days • What is encapsulation? • HAS a relationship • Building HAS a BATHROOM • What is inheritance? • IS A relationship • House IS A building • DOG IS A animal • House extends Building • Object of House can access variables and methods from Building class(Parent) 5/5/2021 Selenium Webdriver 2.0 171
  • 172. POM - Inheritance House IS A building Building.java public class Building { public void getColor() { System.out.println("Color Blue..."); } } House.java public class House extends Building{ } Test.java : Run this script public class test { public static void main(String[] args) { House h = new House(); h.getColor(); }} 5/5/2021 Selenium Webdriver 2.0 172
  • 173. POM - Encapsulation • HAS A relationship • House has a bathroom • Bathroom object can be created inside House class • Bathroom.java public class Bathroom { public int mirrors; public void setMirrors(int m) { mirrors=m; } public int getMirrors() { return mirrors; }} • House.java public class House extends Building{ Bathroom b = null; public House(Bathroom b) { this.b = b; }} • Test.java public class test { public static void main(String[] args) { Bathroom b = new Bathroom(); b.setMirrors(3); House h = new House(b); System.out.println("Mirrors: " + h.b.getMirrors()); }} 5/5/2021 Selenium Webdriver 2.0 173
  • 174. POM • CAR HAS a registration no • Car.java public class Car { String model; RegistrationNo reg; } • RegistrationNo.java public class RegistrationNo { String regno; } • Textcar.java public class TestCar { public static void main(String[] args) { Car c = new Car(); c.model="BMW"; c.reg.regno="ASDASD"; } } 5/5/2021 Selenium Webdriver 2.0 174
  • 175. POM • Page Factory is a class • Twitter.com • More successful where application have similar pages • Create package com.learning.twitter.pages • Configure project for • Selenium • Design Twitter Login page class 5/5/2021 Selenium Webdriver 2.0 175
  • 176. POM Let’s create login functionality with POM framework and run TwitLoginPage.java public class TwitLoginPage { @FindBy(xpath="//*[@id='signin-email']") public WebElement username; @FindBy(xpath="//*[@id='signin-password']") public WebElement password; @FindBy(xpath="//*[@id='front-container']/div[2]/div[2]/form/table/tbody/tr/td[2]/button") public WebElement singin; public void doLogin(String myusername, String mypassword) { username.sendKeys(myusername); password.sendKeys(mypassword); singin.click(); } } 5/5/2021 Selenium Webdriver 2.0 176
  • 177. POM • testTwitLoginPage.java public class testTwitterLoginPage { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("http://twitter.com"); TwitLoginPage lp = PageFactory.initElements(driver, TwitLoginPage.class); lp.doLogin("rishikeshmemane@yahoo.com", "Anupam$100"); } } 5/5/2021 Selenium Webdriver 2.0 177
  • 178. POM • Login page HAS A landing page • Create TwitLandingpage.java • Create 4 FindBy WebElements • Profile • Tweets • Following • Followers • And create 4 different methods each corresponding to each method. • For doLogin method, have TwitLoginPage as return type • And return PageFactory.initElements(driver,TwitLoginPage.class); • Create constructor for both classes which will define driver with one parameter as driver 5/5/2021 Selenium Webdriver 2.0 178
  • 179. POM • Complete Picture/FLow 5/5/2021 Selenium Webdriver 2.0 179
  • 180. POM testTwitterLoginPage.java WebDriver driver = new FirefoxDriver(); driver.get("http://twitter.com"); TwitLoginPage lp = PageFactory.initElements(driver, TwitLoginPage.class); TwitLandingPage landingPage = lp.doLogin("rishikeshmemane@yahoo.com", "Anupam$100"); landingPage.gotoProfile(); Run and check if it successful. Lets automate some more functionalities in twitter.com 5/5/2021 Selenium Webdriver 2.0 180
  • 181. POM TwitLandingPage.java public class TwitLandingPage { WebDriver driver; //constructor public TwitLandingPage(WebDriver driver) { this.driver = driver; } @FindBy(xpath="//*[@id='page-container']/div[1]/div[1]/div/div[2]/div/a") public WebElement profile; @FindBy(xpath="//*[@id='page-container']/div[1]/div[1]/div/div[3]/ul/li[1]/a/span[1]") public WebElement tweets; @FindBy(xpath="//*[@id='page-container']/div[1]/div[1]/div/div[3]/ul/li[2]/a/span[1]") public WebElement following; @FindBy(xpath="//*[@id='page-container']/div[1]/div[1]/div/div[3]/ul/li[3]/a/span[1]") public WebElement followers; public TwitMyProfile gotoProfile() { profile.click(); return PageFactory.initElements(driver, TwitMyProfile.class); } public void gotoTweets() {} public void gotoFollowing() {} public void followers() {} } 5/5/2021 Selenium Webdriver 2.0 181
  • 182. POM • Create TwitMyProfile.java public class TwitMyProfile { @FindBy(xpath="") public WebElement editbutton; WebDriver driver; public TwitMyProfile(WebDriver driver) { this.driver = driver; } public TwitEditProfile editProfile() { editbutton.click(); return PageFactory.initElements(driver, TwitEditProfile.class); } 5/5/2021 Selenium Webdriver 2.0 182
  • 183. POM • Create TwitEditProfile.java public class TwitEditProfile { WebDriver driver; public TwitEditProfile(WebDriver driver) { this.driver = driver; } @FindBy(xpath="") public WebElement inlinediticon; @FindBy(xpath="") public WebElement uploadPhoto; @FindBy(xpath="") public WebElement applyButton; @FindBy(xpath="") public WebElement cancelButton; public void changePic() { inlinediticon.click(); uploadPhoto.sendKeys("E:tempscreenshota.jpg"); applyButton.click(); cancelButton.click(); } public void changeTitle() { } public void caangeSummary() { } } 5/5/2021 Selenium Webdriver 2.0 183
  • 184. POM • Main method public class testTwitterLoginPage { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("http://twitter.com"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); TwitLoginPage lp = PageFactory.initElements(driver, TwitLoginPage.class); // encapsulation TwiLoginPage Has a LandingPage TwitLandingPage landingPage = lp.doLogin("rishikeshmemane@yahoo.com", "Anupam$100"); TwitMyProfile profile = landingPage.gotoProfile(); TwitEditProfile editprofile = profile.editProfile(); editprofile.changePic(); } } 5/5/2021 Selenium Webdriver 2.0 184
  • 185. Useful Links/References • http://yizeng.me/2014/04/25/relationships-between-different- versions-of-selenium/ • http://seleniumeasy.com/ • http://www.toolsqa.com/ • http://www.w3schools.com/cssref/css_selectors.asp • http://www.w3schools.com/js/default.asp - JavaScript 5/5/2021 Selenium Webdriver 2.0 185
  • 186. Documentation • Seleniumhq.org • How to import JAVA documentation in Eclipse? • Copy link from http://docs.seleniumhq.org/download/ web page JavaDoc link • Go to Project->Properties->Java Build Path->Libraries- >Selenium-Java<version> • Edit and paste the copied url removing index.html • Now when mouse is moved on class, help will be shown inline. 5/5/2021 Selenium Webdriver 2.0 186
  • 187. Short Keys 5/5/2021 Selenium Webdriver 2.0 187 ShortKey Action Ctrl+Shift+o Import required classes Alt_Shift+q,c Opens Console Alt+Shift+x,n Run as TestNG test case Ctrl+F11 Run test case as Java application Switch Workspace Alt F+W To Open IDE CTRL+Alt+S
  • 188. Thank You • Email-id: Rishiscorporatetraining@gmail.com • Cell# : +91-9552588168 5/5/2021 Selenium Webdriver 2.0 188
  • 189. Exercise • Login to yahoomail.com • Open a browser, maximize, print window Title • Cucumber exercise for one feature and step file • Print Facebook friends name • Only testing site exercise 5/5/2021 Selenium Webdriver 2.0 189
  • 190. Exercise – Finding links from google.com WebDriver dr = new FirefoxDriver(); dr.get("http://google.com");; dr.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); dr.findElement(By.name("q")).sendKeys("mumbai"); dr.findElement(By.name("q")).sendKeys(Keys.ENTER); WebElement box = dr.findElement(By.xpath("//*[@id='rso']")); List<WebElement> links = box.findElements(By.tagName("a")); int totLinks = links.size(); System.out.println("total links: " + totLinks); for(int i=0;i<totLinks;i++) { if ( links.get(i).isDisplayed() && !(links.get(i).getText().isEmpty()) ) System.out.println(links.get(i).getText() + " -- " + links.get(i).isDisplayed() + " -- " + links.get(i).isEnabled()); } 5/5/2021 Selenium Webdriver 2.0 190
  • 191. Exercise – Autosuggestion from google.com public static WebDriver dr=null; public static void main(String[] args) throws InterruptedException { dr = new FirefoxDriver(); dr.get("http://google.com");; dr.findElement(By.name("q")).sendKeys("mumbai"); Thread.sleep(3000L); String part1 = "//*[@id='sbse"; String part2 = "']/div[2]"; int i=0; while(iselementPresent(part1+i+part2)) { String xpath = part1+i+part2; System.out.println(dr.findElement(By.xpath(xpath)).getText()); i++; } dr.quit();} public static boolean iselementPresent(String pXpath) { int cnt=0; cnt = dr.findElements(By.xpath(pXpath)).size(); if (cnt == 0) return false; else return true; } 5/5/2021 Selenium Webdriver 2.0 191

Notas del editor

  1. // find greatest of 2 numbers int x=12; int y=110; if (x>y) System.out.println("X=" + x + " > Y=" + y); else System.out.println("X=" + x + " < Y=" + y); // find greatest of 3 numbers int p=120; int q=130; int r=140; if ((p>q) && (p>r)) System.out.println("p=" + p + " + is the greatest among q = " + q + " & r="+r); else if (q>r) System.out.println("q=" + q + " + is the greatest among p = " + p + " & r="+r); else System.out.println("r=" + r + " + is the greatest among p = " + p + " & q="+q); }
  2. WebDriver dr = new FirefoxDriver(); /*dr.get("https://addons.mozilla.org/en-us/firefox/addon/firepath/"); // print label "ADD-ONS" System.out.println(dr.findElement(By.xpath("//*[@id='masthead']/h1/a")).getText()); // sendkeys to search box dr.findElement(By.xpath("//*[@id='search-q']")).sendKeys("AAAA"); Thread.sleep(5000L); dr.findElement(By.xpath("//*[@id='search']/input[1]")).sendKeys("BBBB"); Thread.sleep(5000L); dr.findElement(By.name("q")).sendKeys("CCCC"); Thread.sleep(5000L); dr.findElement(By.xpath("//*[@id='page']/div[2]/div/form/input[1]")).sendKeys("DDDD"); // get Text from button System.out.println("Text on button : " + dr.findElement(By.xpath("//*[@id='search']/button")).getAttribute("title")); // findout 'Register' link // xpath System.out.println("Text on link Register : " + dr.findElement(By.xpath("//*[@id='aux-nav']/ul/li[1]/a[1]")).getText()); // another xpath System.out.println("Text on link Register : " + dr.findElement(By.xpath("//*[@class='amo-header']/nav/ul/li[1]/a[1]")).getText()); // another xpath System.out.println("Text on link Register : " + dr.findElement(By.xpath("//*[text()='Register']")).getText()); System.out.println("Text on link Register : " + dr.findElement(By.xpath("//a[@href='/en-us/firefox/users/register']")).getText()); // contains function dr.findElement(By.xpath("//input[contains(@class,'text')]")).sendKeys("EEEE"); */ dr.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1#identifier"); // find text on Need help link using linktext System.out.println("Link text : " + dr.findElement(By.linkText("Need help?")).getText()); // find text on Forgot Password link using partial linktext System.out.println("Partial Link text : " + dr.findElement(By.partialLinkText("Need")).getText()); // and condition to identify enter your email // and condition to identify enter your email dr.findElement(By.xpath("//*[@id='Email' or @name='WrongEmail']")).sendKeys("rishiscorporatetraining@gmail.com"); Thread.sleep(5000L); dr.findElement(By.xpath("//*[@id='Email' or @name='WrongEmail']")).clear(); dr.findElement(By.xpath("//*[@id='Email' and @type='email']")).sendKeys("rishimemane@gmail.com"); dr.findElement(By.xpath("//*[@value='Next' and @id='next']")).click(); Thread.sleep(3000L); // Enter password dr.findElement(By.xpath("//*[@id='Passwd' and @type='password' and @name='Passwd']")).sendKeys("Anupam$100"); Thread.sleep(3000L); // click on Signin button using name locator dr.findElement(By.xpath("//*[@id='signIn']")).click();
  3. gmail.com To get CssSelector, change Xpath to Css in Firebug window CSSSelectors are case sensitive - Capital and small letters matter To enter username #Email [id='Email'] input[id='Email'] Even space will matter in CSSSector [type='email'] AND condition [name='Email'][type='email'] Starts with Em string input[name^='Em'] Click on SignIn Buttton: [name='signIn'] Ends with In string input[name$='In'] contains with ign string input[name*='ign'] To specify “Create an Account” link #link-signup>a Or #link-signup a Or [id='link-signup'] a Or [id='link-signup']>a To find out all inputs present on webpage Input To find out all links present on webpage a To select all nodes * Selects all <p> elements inside <div> elements div p Select second input (similar to input[2] in xpath) input:nth-child(2)
  4. ----------------------------------------------------- Print all links in Golf Club main menu WebDriver dr = new FirefoxDriver(); dr.get("http://www.americangolf.co.uk/"); Actions act = new Actions(dr); WebElement element = dr.findElement(By.xpath("//*[@id='navigation']/nav/ul/li[1]/a")); act.moveToElement(element).build().perform(); WebElement box = dr.findElement(By.xpath("//*[@id='CLUBS_1']/div[1]")); List<WebElement> links = box.findElements(By.tagName("a")); System.out.println("links.size : " + links.size()); for (int i=0;i<links.size();i++) System.out.println(links.get(i).getText()); --------------------------------------------------- Move price slider by 100 in Americanglofclub.com WebDriver dr = new FirefoxDriver(); dr.get("http://www.americangolf.co.uk/golf-clubs/drivers?pmax=430&pmin=30"); Actions act = new Actions(dr); WebElement element = dr.findElement(By.xpath("//*[@id='secondary']/div[1]/div[2]/div[1]/div[1]/span[1]")); act.dragAndDropBy(element, 100, 0).build().perform(); ---------------------------------------------------
  5. Webtable handling WebDriver dr = new FirefoxDriver(); dr.get("http://www.w3schools.com/html/html_tables.asp"); /*// cell wise display List<WebElement> table = dr.findElements(By.xpath("//table[@class='reference']/tbody/tr/td")); for(int i=0;i<table.size();i++) System.out.println(table.get(i).getText()); // row-wise display List<WebElement> table = dr.findElements(By.xpath("//table[@class='reference']/tbody/tr")); for(int i=0;i<table.size();i++) System.out.println(table.get(i).getText()); */ // col-wise display List<WebElement> table = dr.findElements(By.xpath("//table[@class='reference']/tbody/tr/td[1]")); for(int i=0;i<table.size();i++) System.out.println(table.get(i).getText());