You are on page 1of 51

TestNG Web Driver

Simona Pitam
Understand Selenium Locators And Master CSS/XPath

What Is XPath?

XPath is a technique for uniquely identifying an element on a web page. It behaves like an address to an HTML

element such as check boxes, text, images, links, and divs, etc. In Selenium, we treat XPath as one of the most

trusted element locators. XPath is much more than an address as it not only points to the end point, it also

contains the whole map to lead to a destination.


Simona Pitam
XPATH Types
1) Absolute XPath

2) Relative XPath

The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can
select the element from the root node.

Example of abs Xpath://input[@id='twotabsearchtextbox']


Simona Pitam
Example of relative Xpath://input[@id='twotabsearchtextbox']
XPATH Differences
5 d

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Always Relative Xpaths are preferred as they are not the complete paths from the Root element. (//html//body)
Beacuse in future any of the webelement when added/Removed then Absolute Xpath changes.

So Always use Relative Xpaths in your Automation. Simona Pitam


Absolute Xpath & Relative Xpath
An absolute xpath in HTML DOM starts with /html e.g.

/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]

and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.

.//*[@id='answers']/h2[1]/a[1]

Simona Pitam
XPATH Allocation in Chrome
Add Chrome Extension

ChroPath

Right Click

Inspect

Click on >> ChroPath Simona Pitam

Select Element & see Xpath absolute or Relative


Locators in Selenium

There are a total of 8 locators in Selenium WebDriver-

By Id - Locates element using id attribute of the web element.

WebElement element = driver.findElement(By.id("elementId"));

By className - Locates the web element using className attribute.


Simona Pitam
WebElement element = driver.findElement(By.className("elementsClass"));
Selenium Locators
By tagName - Locates the web element using its html tag like div, a, input etc.

WebElement element = driver.findElement(By.tagName("a"));

By name - Locates the web element using name attribute.

WebElement element = driver.findElement(By.name("male"));


By linkText - Locates the web element of link type using their text. Simona Pitam

WebElement element = driver.findElement(By.linkText("Click Here"));


Selenium Locators
By partialLinkText - Locates the web element of link type with partial matching of text.

WebElement element = driver.findElement(By.partialLinkText("Click"));


By cssSelector - Locates the web element using css its CSS Selector patterns(explained in
detailed here - CSS Locators).
WebElement element = driver.findElement(By.cssSelector("div#elementId"));

By xpath - Locates the web element using its XPaths(explained in detailed here Simona Pitam

WebElement element = driver.findElement(By.xpath("//div[@id=’elementId’]"));


Selenium Locators
Now you have successfully learnt how to locate elements in Selenium. As you can see locating
element by id, className, tagName, name, linkText and partialLinkText is simple. We just have
to select the right locator based on the uniqueness of the element e.g. we prefer using id
because id of elements are generally unique. But there can be scenarios where we might not
have id attributes of web elements, also other locators like name, className might not fetch the
unique required web element. In those scenarios, we should use cssSelector and xpath locators.
These locators are very powerful and help in creating robust locators for complex web elements.
We have dedicated separate tutorials for these two locators in our coming posts- CSS
Simona Pitam
Locatorsand XPath Locators
CSS Locators
SS stands for Cascading Style Sheets, these are used for styling the different elements of an
HTML webpage. In the .css files we can locate specific elements of a webpage(.html files) and
then style them like - set their font size, width, height etc.

For locating the web elements to be styled, we use certain rules provided as CSS Selectors.

For example, the following statement first locates a web element satisfying the selector pattern -
"div#searchBox" and then aligns the text inside it to center.
div#searchBox {text-align: center;} Simona Pitam
CSS Locators
In Selenium, we can use these CSS Selector rules/patterns for locating web elements and later
perform different operations on them. For example-
//Locating searchBox element using CSS Selector
WebElement searchBox = driver.findElement(By.cssSelector("div#searchBox"));

//Performing click operation on the element


searchBox.sendKeys("ArtOfTesting");

Simona Pitam
Using Drop Down Box in Selenium
Explanation of Application under Test

We have designed the web page in a way to include a few fundamental types of web elements.

● Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-directs
the user to “https://www.google.co.in/” and “http://www.abodeqa.com/” respectively on the click
event.
● Dropdown: The three dropdowns have been created for selecting colours, fruits and animals with a
value already set to default.
● Button: A “try it” button has been created to show up the pop up box having Ok and Cancel button Simona Pitam
upon click event.
Scenario to be Automated

Scenario to be automated
● Launch the web browser and open the webpage
● Click on the “Google” hyperlink
● Navigate back to the original web page
● Select the “Green” in colour dropdown
● Select the “Orange” in the fruit dropdown
● Select the “Elephant” in the animal dropdown Simona Pitam
How to Handle Drop - Down Box
<div>

<select id="SelectID_One">

<option value="redvalue">Red</option>

<option value="greenvalue">Green</option>

<option value="yellowvalue">Yellow</option> Simona Pitam

<option value="greyvalue">Grey</option>

</select>
Selenium Example
// select the first operator using "select by value"

Select selectByValue = new Select(driver.findElement(By.id("SelectID_One")));

selectByValue.selectByValue("greenvalue");
Simona Pitam

Thread.sleep(5000);
Selenium Example
// / select the second dropdown using "select by visible text"

Select selectByVisibleText = new Select (driver.findElement(By.id("SelectID_Two")));

selectByVisibleText.selectByVisibleText("Lime");
Simona Pitam

Thread.sleep(5000);
CheckBox Element in Web Driver

By ID
If ID is given for the Radio Button/CheckBox and you just want to click on it irrespective of it’s value, then the
command will be like this:
WebElement radioBtn = driver.findElement(By.id("toolsqa"));

radioBtn.click();

Simona Pitam
With Is Selected CheckBox
If your choice is based on the pre-selection of the Radio Button/Check Box and you just need to select the
deselected Radio Button/Check Box. Assume there are two Radio Buttons/Check Boxes, one is selected by
default and you want to select the other one for your test. With IsSelected statement, you can get to
know that the element is selected or not.

Simona Pitam
Example with Value
// Find the checkbox or radio button element by Name

List oCheckBox = driver.findElements(By.name("tool"));

// This will tell you the number of checkboxes are present

int iSize = oCheckBox.size();

// Start the loop from first checkbox to last checkboxe

for(int i=0; i < iSize ; i++ ){

// Store the checkbox name to the string variable, using 'Value' attribute

String sValue = oCheckBox.get(i).getAttribute("value");


Simona Pitam
// Select the checkbox it the value of the checkbox is same what you are looking for

if (sValue.equalsIgnoreCase("toolsqa")){

oCheckBox.get(i).click();

// This will take the execution out of for loop

break;
Practise Exercise
Practice Exercise

1. Launch new Browser


2. Open “http://toolsqa.wpengine.com/automation-practice-form/“
3. Challenge One – Select the deselected Radio button (female) for category Sex (Use IsSelected
method)
4. Challenge Two – Select the Third radio button for category ‘Years of Exp’ (Use Id attribute to select
Radio button)
5. Challenge Three – Check the Check Box ‘Automation Tester’ for category ‘Profession'( Use Value
attribute to match the selection) Simona Pitam
6. Challenge Four – Check the Check Box ‘Selenium IDE’ for category ‘Automation Tool’ (Use
cssSelector)
CSS Selector in Selenium
In WebDriver, in order to interact with a web element, such as clicking, or typing, we first need to locate the elements.

There are different ways we can locate elements in WebDriver. In this WebDriver tutorial, we look at how we can use CSS
Selectors in more detail and with examples to interact with web elements.

Using CSS selectors to locate elements has some benefits:

1. It’s faster;
Simona Pitam
2. It’s more readable;

3. It’s more used.


Locating Elements by Attribute

Let’s imagine we have a tag with the following attributes [id, class, name, value]

<input type="text" id="fistname" name="first_name" class="myForm">

The generic way of locating elements by their attribute in CSS Selectors is

css = element_name[<attribute_name>='<value>']

e.g.css=input[name=’first_name’] Simona Pitam

We can use the same approach to locate by id and class attributes, however, there are short forms
that we can use to make it more readable.
CSS Selectors
We can use the same approach to locate by id and class attributes, however, there are short forms
that we can use to make it more readable.

In CSS, we can use # notation to select the id:

css="input#firstname" or just css="#firstname"

We can also use the . notation to select the class


Simona Pitam
css="input.myForm" or just css=".myForm"

Take extra care when using the short form notations, especially the . class notation as there could
be many web elements on the html source with the same class attribute.
CSS Selectors in Web Driver
The value of the display could either be “none” or “block” depending on the ajax call. In this
situation we have to locate the element by both class and style.

We could use

css="div[class='ajax_enabled'] [style='display:block']"

Simona Pitam
Locating Child Element
As can be seen, the individual list
<div id="child"><img src="./logo.png"></div> elements don’t have any id
associated with them. If we want to
To locate the image tag, we would use: locate the element with text
css="div#child img"
‘Orange’, we have to use “nth-of-
type”
Multiple Selections:
There are occasions when there are multiple child elements within the same parent element such as list elements

Simona Pitam
<ul id="fruit"> css="ul#fruit li:nth-of-
<li>Apple</li>
type(2)"
<li>Orange</li>
<li>Banana</li>
</ul>
Locating Child Element
Similarly, if we need to select the last child element, i.e. ‘Banana’, we can use

css="ul#fruit li:last-child"

Simona Pitam
Strings & Randomly Generated Id’s
We can also use string matchers to locate elements:

<div id="123_randomId">
<div id="randomId_456">
<div id="123_pattern_randomId">

To select the first div element, we would use ^= which means ‘starts with’: Simona Pitam

css="div[id^='123']"
Strings & Randomly Generated Id’s
To select second div element, we would use $= which means ‘ends with’:

css="div[id$='456']"

To select the last div element we would use *= which means ‘sub-string’

css="div[id*='_pattern_']"
Simona Pitam

We can also use the ‘contains’

css="div:contains(_pattern_)"
Attribute not Contain a Specific Value
In WebDriver, how do you find elements whose attribute contain values which you don’t want to
select? This CSS selector example shows how NOT to select by specific attribute value

Suppose you have many elements which share the same attribute and attribute value, but some of
those elements have other variables appended to the value. E.g:

<div class="day past calendar-day-2017-02-13 calendar-dow-1 unavailable">


Simona Pitam
<div class="day today calendar-day-2017-02-14 calendar-dow-2 unavailable">
<div class="day calendar-day-2017-02-15 calendar-dow-3">
<div class="day calendar-day-2017-02-16 calendar-dow-4">
Attribute not Contain a Specific Value
In the above snippet, we want to select an available day (i.e. the two last divs)

As can be seen, all four divs contain “calendar-day-” but the first two also contain “unavailable”
which we don’t want.

The CSS selector for Not selecting the first two divs is

css = "div[class*=calendar-day-]:not([class*='unavailable'])"
Simona Pitam
Find Web Driver Elements
In the previous chapter of WebElement Commands, we learned different types to actions which can be
performed on a WebElement object. Thus the next thing to do is to interact with a web page to use
WebElement Commands/Actions. First thing to locate an element on the web page before interacting with it
and locating elements can be done on the WebDriver Instance(driver) itself or on a WebElement.
WebDriver gives us Find Element and Find Elements methods to locate element on the web page.

As in the previous chapters we learned that every method of the WebDriver either returns something or
return void(means return nothing). The same way findElementmethod of WebDriver returns WebElement.

Simona Pitam
Find Element in Web Driver
By ID
id(String id) : By – This is the most efficient and preferred way to locate an element, as most of the times
IDs are unique. It takes a parameter of String which is a Value of ID attribute and it returns a BY object to
findElement() method.

Command – driver.findElement(By.id(“Element ID”));

With this strategy, If no element has a matching id attribute, a NoSuchElementException will be raised.

Example: If an element is given like this: Simona Pitam


Actual Command:
WebElement element = driver.findElement(By.id("submit"));
// Action can be performed on Input Button element
element.submit();
Simona Pitam

Find Element by TAG


Find Element By TAG
Actual Code:

WebElement element = driver.findElement(By.tagName("button"));


// Action can be performed on Input Button element
element.submit();

Simona Pitam
Multi Browsing Testing in TestNG
In every project it is required to perform multi-browser testing to make sure that the functionality is working
as expected with every browser to give equal user experience to all of the wide range of audience. It takes a
considerable time to test everything on every browser and when we have used automation to reduce the
testing efforts then why don’t we perform the multi-browser testing using automation. TestNG gives us
functionality to perform same test on different browsers in a simple and easy way.

How to do it…

Simona Pitam
Multi Browsing TEsting Example
How to do it…

1)Create your Script to test a LogIn application using TestNG class.

2) Pass ‘Browser Type’ as parameters using TestNG annotations to the before method of the TestNG class.
This method will launch only the browser, which will be provided as parameter.

Simona Pitam
Code Example
Code Example you can find in my git hub in following link:

https://github.com/simonapitam/seleniuntutorial

Simona Pitam
Creating XML File
Create a TestNG XML for running your test. Configure the TestNG XML for passing parameters i.e. to tell which
browser should be used for Running the Test.

See in Gut hub

Simona Pitam
Negative Testing in Selenium
While it is definitely important to verify that the software performs its basic functions as intended, it is equally or
more important to verify that the software is able to gracefully handle an abnormal situation. It is obvious that most
of the defects arise out of generating such situations with reasonable and acceptable creativity from the testers.

Simona Pitam
Simona Pitam

Positive Testing
Positive testing
Positive testing, many times referred to as “Happy path testing” is generally the first form of testing that a tester
would perform on an application. It is the process of running test scenarios that an end user would run for his use.
Hence as implied, positive testing entails running a test scenario with only correct and valid data. If a test scenario
doesn’t need data, then positive testing would require running the test exactly the manner in which it’s supposed to
run and hence to ensure that the application is meeting the specifications.

Sometimes there may be more than one way of performing a particular function or task with an intent to give the
end user more flexibility or for general product consistency. This is called alternate path testing which is also a kind
of positive testing. In alternate path testing, the test is again performed to meet its requirements but using the
different route than the obvious path. The test scenario would even consume the same kind of data to achieve the
same result.
Simona Pitam

Negative Testing
Negative testing
Negative testing commonly referred to as error path testing or failure testing is generally done to ensure the
stability of the application.

Negative testing is the process of applying as much creativity as possible and validating the application against
invalid data. This means its intended purpose is to check if the errors are being shown to the user where it’s
supposed to, or handling a bad value more gracefully.

It is absolutely essential to understand why negative testing is necessary.

The application or software’s functional reliability can be quantified only with effectively designed negative
scenarios. Negative testing not only aims to bring out any potential flaws that could cause serious impact on the
consumption of the product on the whole but can be instrumental in determining the conditions under which the
application can crash. Finally, it ensures that there is sufficient error validation present in the software.
Practical Example

Simona Pitam
Requirements for Test
Requirements:

● The name text box is a mandatory parameter


● The description is not mandatory.
● The name box can have only a-z and A-Z characters. No numbers, special characters are allowed.
● The name can be maximum 10 characters long.

Simona Pitam
Positive Cases
Positive test cases: Below are some positive testing scenarios for this particular pane.

1. ABCDEFGH (upper case validation within character limit)


2. abcdefgh lower case validation within character limit)
3. aabbccddmn (character limit validation)
4. aDBcefz (upper case combined with lower case validation within character limit)
5. .. and so on.

Simona Pitam
Negative Cases
Negative test cases: Below are some negative testing scenarios for this particular pane.

1. ABCDEFGHJKIOOOOOKIsns (name exceeding 10 characters)


2. abcd1234 (name having numerical values)
3. No name supplied
4. sndddwwww_ ( the name containing special characters)
5. .. and so on.

Simona Pitam
Logging

Why logging is important in any application?


Logging is very important to any application. It helps us collect information about how the application is
running and also helps us debug if any failure occurs.

Simona Pitam
Simona Pitam

Log4J
What is Log4j?
Log4j is a brilliant logging API available both on Java and .net framework. Advantages are:

– Log4j allows you to have a very good logging infrastructure without putting in any efforts.

– Log4j gives you the ability to categorize logs at different levels (Trace, Debug, Info, Warn, Error and Fatal).

– Log4j gives you the ability to direct logs to different outputs. For e.g. to a file, Console or a Database.

– Log4j gives you the ability to define the format of output logs.

– Log4j gives you the ability to write Asynchronous logs which helps to increase the performance of the
application.

– Loggers in Log4j follow a class hierarchy which may come handy to your applications.

If you are not able to understand any of these points than don’t worry. Things will get clearer as we approach
to the end of Log4j Tutorial series.
Simona Pitam

Log4j

Log4j
Log4j consists of four main components

– LogManager

– Loggers

– Appenders

– Layouts

With these comes some additional components which will be covered in the individual headings in following
tutorials
Log4j
package Log4jSample;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class SampleEntry {

//mainLogger is a logger object that we got from LogManager. All loggers are
//using this method only. We can consider LogManager as a factory to create
//Logger objects
static Logger mainLogger = LogManager.getLogger(SampleEntry.class.getName());
Simona Pitam
public static void main(String[] args) {
// TODO Auto-generated method stub

BasicConfigurator.configure();
mainLogger.info("This is just a logger");

}
}
Loggers

Logger
This is a class which helps you log information at different logging levels. In the above sample code you can
see that we have created a logger named mainLogger using the LogManager static class. Now we can use it to
write logs. As you can see we have mainLogger.info(“Comments that you want to log”) statement which logs
the string.

Simona Pitam

You might also like