You are on page 1of 87

Selenium Web driver

1. What is selenium webdriver and how it help us in software testing process?


Webdriver in selenium (http://docs.seleniumhq.org/projects/webdriver/) is an Interface and it is
designed to overcome some limitations of selenium RC software testing tool. However selenium
WebDriver's development is in process so still there are few limitations and known issues available
in selenium WebDriver. Selenium WebDriver is also known as Selenium 2 and used for web as well
mobile
applications testing. It is freeware software testing tool and mostly used as a regression testing tool
for web and mobile applications.
Selenium 2 supports most of all browsers to run your test cases and many programming languages
like C#, Java, Python, Ruby, .Net, Perl, PHP, etc.. to create and modify your test scripts. Selenium
2(WebDriver) controls browser directly from operating system level so it is interacting very fast and
with more realistic way with browsers. Major people in world using Selenium webdriver with java.
2. Difference between WebDriver and selenium RC
WebDriver

Selenium WebDriver do not require selenium server for running test.

WebDriver is using native automation from each and every supported language for running
automation scripts on browsers.

WebDriver supports web as well mobile application testing so you can test mobile applications
(iPhone or Android).

Supporting latest versions of almost all browsers.

WebDriver controls the browser itself.

Selenium RC

Required selenium server for running test.

Selenium RC is using JavaScripts to drive automation with browser.

Selenium RC supports only web application testing.

Supporting all browsers but not supporting latest versions.

Selenium RC is using javascript to interact and operate on web page

You can share if you know any limitations or advantages of Selenium WebDriver by posting
comments bellow.
Click here (http://docs.seleniumhq.org/projects/webdriver/) to read more about WebDriver. You
can read my next post about selenium webdriver download install.
selenium web driver, selenium webdriver documentation, selenium testing, webdriver selenium,
selenium testing tool, selenium driver, selenium tool, automated testing tools, software testing tools,
selenium automation, selenium webdriver vs remote control, selenium online training, selenium
training, selenium test, selenium test tool, webdriver, automated testing tools, web testing tools, test
automation tools, selenium firefox webdriver.

Page 1 of 87

3. How to download and install Selenium Webdriver with Eclipse and Java Step By
Step
Download selenium webdriver and install selenium webdriver is not much more hard. Actually
there is nothing to install except JDK. Let me describe you step by step process of download,
installation and configuration of web driver and other required components. You can view my post
about "What is selenium webdriver" if you wants to know difference between WebDriver and
selenium RC software tool.
(Note : I am suggesting you to take a tour of Basic selenium commands tutorials with examples
before going ahead for webdriver. It will improve your basic knowledge and helps you to create
webdriver scripts very easily. )
Steps To Setup and configure Selenium Webdriver With Eclipse and Java
(Note : You can View More Articles On WebDriver to learn it step by step)
Step 1 : Download and install Java in your system
First of all you need to install JDK (Java development kit) in your system. So your next question will
be "how can i download java" Click here to download Java and install it in your system as per given
installation guide over there.
Step 2 : Download and install Eclipse
Download Eclipse for Java Developers and extract save it in any drive. It is totally free. You can run
'eclipse.exe' directly so you do not need to install Eclipse in your system.
Step 3 : Download WebDriver Java client driver.
Selenium webdriver supports many languages and each language has its own client driver. Here we
are configuring selenium 2 with java so we need 'webdriver Java client driver'. Click here to go on
WebDriver Java client driver download page for webdriver download file. On that page click on
'Download' link of java client driver as shown in bellow image.

(language-specific client driver's version is changing time to time so it may be different version when
you will visit download page. )
Downloaded 'webDriver Java client driver' will be in zip format. Extract and save it in your system at
path D:\selenium-2.33.0. There will be 'libs' folder, 2 jar files and change log in unzipped folder as
shown in bellow figure. We will use all these files for configuring webdriver in eclipse.

Step 4 : Start Eclipse and configure it with selenium 2 (webdriver)

Select WorkSpace on eclipse start up

Double click on 'eclipse.exe' to start eclipse. First time when you start eclipse, it will ask you to select
your workspace where your work will be stored as shown in bellow image. Create new folder in D:
drive with name 'Webdriverwork' and select it as your workspace. You can change it later on from
'Switch Workspace' under 'file' menu of eclipse.

Page 2 of 87

After selecting workspace folder, Eclipse will be open.

Create new project

Create new java project from File > New > Project > Java Project and give your project name
'testproject' as shown in bellow given figures. Click on finish button.

Now your new created project 'testproject' will display in eclipse project explorer as bellow.
Page 3 of 87

Create new package

Right click on project name 'testproject' and select New > Package. Give your package name =
'mytestpack' and click on finish button. It will add new package with name 'mytestpack' under
project name 'testproject'.

Create New Class

Right click on package 'mytestpack' and select New > Class and set class name = 'mytestclass' and
click on Finish button. It will add new class 'mytestclass' under package 'mytestpack'.

Page 4 of 87

Now your Eclipse window will looks like bellow.

Add external jar file to java build path

Now you need to add selenium webdriver's jar files in to java build path.

Right click on project 'testproject' > Select Properties > Select Java build path > Navigate to
Libraries tab

Click on add external JARs button > select both .jar files from D:\selenium-2.33.0.

Click on add external JARs button > select all .jar files from D:\selenium-2.33.0\libs

Now your testproject's properties dialogue will looks like bellow.

Page 5 of 87

That's all about configuration of WebDriver with eclipse. Now you are ready to write your test in
eclipse and run it in WebDriver.
You can Read My Post about how to write and run your first test in WebDriver.
download selenium webdriver, install webdriver, download webdriver selenium, selenium testing,
selenium testing tool, how to download selenium webdriver, what is selenium webdriver, webdriver
download, selenium webdriver download, selenium automation, selenium download, selenium install,
install selenium webdriver, install selenium webdriver in eclipse, eclipse and selenium, java and
selenium, how to install a server, selenium driver, how to setup selenium webdriver, download
webdriver selenium, selenium webdriver tutorial java.

4. Create And Run First Webdriver Script With Eclipse


Run First Webdriver Script
You need to install webdriver with eclipse to run your script in webdriver. After installation of
webdriver, You need to write a java code in eclipse for your test case of software web application. Let
me give you one simple example of creating simple webdriver script. First of all you need to write
code as bellow in your
'mytestclass.java' file. You can request(if you wish) this sample code file by submitting comment
bellow with your email id.

Now you are ready to run your script from Run menu as shown bellow.

Script Explanation
Page 6 of 87

Above script will open Firefox browser.

Then driver.get syntax will open 'http://only-testing-blog.blogspot.in/' in firefox browser.

Then driver.getCurrentUrl() will get the current page URL and it will be stored in variable
'i'. You can do same thing using "storeLocation" command in selenium IDE

And at last, it will print value of variable in console as shown bellow.

So this is the simple webdriver script example. You can create it for your own software web application
too by replacing URL in above script. We will learn more scripts in detail in my upcoming posts.
Running Selenium Webdriver Test In Google Chrome
You can read my THIS POST to know how to run selenium webdriver test of software
application in Mozilla Firefox browser. As you know, webdriver support Google Chrome
browser too. You need to do something extra for launching webdriver test in in Google
chrome browser. Let me describe you steps to launch webdriver test in Google Chrome.
Download ChromeDriver server
First of all, download latest version of ChromeDriver server for webdriver. You can download
it directly from http://code.google.com/p/chromedriver/downloads/list. Current latest
version for win32 is chromedriver_win32_2.3 as shown bellow.

Click on that link. It will take you to download page.

Click on link shown above to download chrome driver zip file. On completion of download,
extract zip file to D:/ drive.
Now in eclipse, create new project with name = 'chromeproject' and create new class with
name = 'chromebrowser'. Don't forget to select 'public static void main(String[] args)'
Page 7 of 87

method during new java class creation. Write code as shown bellow in class file. You can
request this copy of this code by submitting comment bellow this post.

Look in to above image. I set path for Google chrome driver as


System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32_2.3\\chro
medriver.exe");
So now, your test will run in Google chrome browser.

5. Different Ways Of Locating Elements In WebDriver


1) Selenium Webdriver Element Locator - Locating Element By Name With
Example
Selenium WebDriver/Selenium 2 is web and mobile application regression testing tool
and it is using element locators to find out and perform actions on web elements. We
have learn Element Locating by ID, Element Locating By Tag Name and Locating
element by Class Name with examples in my previous
posts. Locating Element By Name is very useful method and many peoples are using
this method in their webdriver automation test case preparation. Locating Element By
Name and Locating Element by ID are nearly same. In Locating Element by ID method,
webdriver will look for the specified ID attribute and in Locating Element By Name
method, webdriver will look for the specified Name attribute.
Let me show you one example of how to locate element by name and then we will use it
in our webdriver test case.

Look in to above image, web element 'First Name' input box do not have any ID so
webdriver can not locate it By ID but that element contains name attribute. So
webdriver can locate it By Name attribute. Syntax of locating element in webdriver is as
bellow.
driver.findElement(By.name("fname"));
Now let we use it in one practical example as bellow.Copy bellow given @Test method
part and replace it with the @Test method part of example given on this page.
Page 8 of 87

(Note : @Test method is marked with pink color in that example).


@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by Name and type given texts in to input box.
driver.findElement(By.name("fname")).sendKeys("My First Name");
}

Above example will type the text in text box using By Name element locating method.

2) Element Locators In Selenium 2 or WebDriver - Locating Element By Tag


Name
We have learn about Locating element by ID and Locating element by Class
Name with examples in my previous posts. Let me repeat once more that if element
contains ID then we can locate element by its ID and if element do not have ID and
contains Class Name then we can locate an element by Class Name.
Now supposing, web element do not have any ID or Class Name then how to locate that
element in selenium WebDriver ? Answer is there are many alternatives of selenium
WebDriver element locators and one of them is Locating Element By Tag Name.
Locating Element By Tag Name is not too much popular because in most of cases, we
will have other alternatives of element locators. But yes if there is not any alternative
then you can use element's DOM Tag Name to locate that element in webdriver.

(Note : You can view all tutorials of webdriver element locators)


Look in to above image. That select box drop down do not have any ID or Class Name.
Now if we wants to locate that element then we can use it's DOM tag name 'select' to
locate that element. Element locator sysntex will be as bellow.
driver.findElement(By.tagName("select"));
Bellow given example will locate dropdown element by it's tagName to store its values
in variable. Copy bellow given @Test method part and replace it with the @Test method
part of example given on this page.(Note : @Test method is marked with pink color in
that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by tagName and store its text in to variable dropdown.
String dropdown = driver.findElement(By.tagName("select")).getText();

Page 9 of 87

System.out.print("Drop down list values are as bellow :\n"+dropdown);


}

3) How To Locate Element By XPATH In Selenium 2/WebDriver With Example


We have learnt most of all the way of locating element in webdriver like Locating
Element By ID, Locating Element By Name, Locating Element By Class Name,
Locating Element By Tag Name, Locating Element By Link Text Or Partial Link
and Locating Element By CSS Selector. One
another method of locating element in selenium webdriver is By XPATH of element. It is
most popular and best way to locate element in WebDriver. However you can use other
ways too to locate element.
You can write Xpath of any element by many different ways as described in This Post.

Above given image shows the firebug view of First name text box. Now let me give you
few examples of how to write syntax to locate it in webdriver using xPath in 2 different
ways.
1. driver.findElement(By.xpath("//input[@name='fname']"));
2. driver.findElement(By.xpath("//input[contains(@name,'fname')]"));
I have used xPath to locate element in above both the syntax. We can use anyone from
above to locate that specific element. Let we use it in practical example as bellow.
Copy bellow given @Test method part and replace it with the @Test method part of
example given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");//Locate element by cssSelector and then type the text in it.
}

Page 10 of 87

4) Selenium WebDriver By.cssSelector Element Locators With Example


WebDriver support many different element locating methods and locating element
by it's CSS Path is one of the most popular way in webdriver. If you not want to use by
id, name, tag name, class name or link text as your locator then you can locate that
element by it's CSS path. Read this tutorial to learn different ways of writing CSS path
of any element. You can get CSS path of any element using selenium IDE too by setting
CSS as your Locator Builders Preference and then performing some action on that
element in Selenium IDE recording mode. You can get CSS path of any element by
Firebug too.
Now let we learn how we can use By.cssSelector in webdriver. Look in to bellow given
image.

Here we can locate input box First name using bellow given webdriver syntax.
driver.findElement(By.cssSelector("input[name='fname']"));
Bellow given example will locate input box by CSS Selector to type text in it.
Copy bellow given @Test method part and replace it with the @Test method part of
example given on this page.
(Note : @Test method is marked with pink color in that example).
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15,
TimeUnit.SECONDS);
driver.findElement(By.cssSelector("input[name='fname']")).sendKeys("My
Name");;//Locate element by cssSelector and then type the text in it.
}

5) How To Locate Element By Link Text Or Partial Link Text In Selenium


WebDriver

Page 11 of 87

In my previous posts what we have learn is we can Locate Element By Name, Locate
Element By ID, Locate Element By Class Name And Locate Element By Tag
Name to take any action on that element. We will look about different web driver
actions and operations in my upcoming posts. Now let we learn two more element
locators as bellow.
Locate Element By Link Text
If your targeted element is link text then you can use by link text element locator to
locate that element. Look in to bellow given image.

My Targeted element Is Link text 'Click Here' and I wants to click on It then I can use It
as bellow.
driver.findElement(By.linkText("Click Here")).click();
Locate Element By Partial Link Text
Same as Link text, We can locate element by partial link text too. In that case we need
to use By.partialLinkText at place of By.linkText as bellow.
driver.findElement(By.partialLinkText("Click ")).click();
For locating element by link text, we need to use full word 'Click Here' but in case of
locating element by partial link text, we can locate element by partial work 'Click' too.
Look in to bellow given example. I have used both the element locators to locate links.
Copy bellow given @Test method part and replace it with the @Test method part of
example given on this page. (Note : @Test method is marked with pink color in that
example).

@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.linkText("Click Here")).click();//Locate element by
linkText and then click on it.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("18:"))); /
/Locate element by partial linkText.
}

Page 12 of 87

6) Locating Web Element By ClassName In Selenium WebDriver with example


There are many different ways of locating elements in webdriver for your software web
application page and I have described one of them in my PREVIOUS POST with
example. In webdriver, we can't do any thing on web page if you don't know how to
locate an element. As you know, we can use element's ID to locate that specific element
but suppose if your element do not have any ID then how will you locate that
element ? Locating web element by className is good alternative if your element
contains class name. We can locate element By Tag Name, By Name, By Link Text, By
Partial Link Text, By CSS and By XPATH too but will look about them in my next posts.
How to get the class name of element
You can get the class name of element using firebug as shown in bellow given image.

Look in to above image. Post date content has a class and we can use that class name
to store that blog post date string. Notice one more thing in above image, blog post
date string has not any ID so we can not locate it by ID.
(Note : You can view more webdriver tutorials on THIS LINK.)
Example Of Locating Web Element By ClassName
We can use bellow given syntax to locate that element.
driver.findElement(By.className("date-header"));
Practical example of locating web element by className is as bellow.
package junitreportpackage;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;

public class Mytest1 {


//To open Firefox browser
WebDriver driver = new FirefoxDriver();
@Before
public void beforetest() {

Page 13 of 87

//To Maximize Browser Window


driver.manage().window().maximize();
//To Open URL In browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@After
public void aftertest() {
driver.quit();
}
@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
String datentime = driver.findElement(By.className("dateheader")).getText();//Locating element by className and store its text to
variable datentime.
System.out.print(datentime);
}
}

7) How To Locate Elements By ID In Selenium WebDriver With Example


Before using WebDriver, You must be aware about different ways of locating an
elements
in
WebDriver.
Locating
an
element
is
essential
part
in
selenium WebDriver because when you wants to take some action on element (typing
text or clicking on button), first you need to locate that specific element to perform
action.
First of all I recommend you to read all these selenium IDE element locating
methods and then read this article about Selenium WebDriver element locators to get
all locating methods in better way.
WebDriver which is also known as a Selenium 2 has many different ways of locating
element. Let me explain each of them with examples. Here I am explaining how to
locate element By id and will describe Locating Web Element By ClassName in my
Next Post and others in latter posts.
Locating UI Element By ID
If your webpage element has unique and static ID then you can locate your page
element by ID. Look in to bellow given image. You can verify that your webelement has
any id or not using the firebug.

Page 14 of 87

In above image, Submit Query button has unique id = 'submitButton'. I can use that id
to locate button as bellow.
driver.findElement(By.id("submitButton"));
Bellow given example will show you how to locate element by id and then how to click
on it. Copy bellow given @Test method part and replace it with the @Test method part
of example given on this page.(Note : @Test method is marked with pink color in that
example).
@Test
public void test() {
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for (int i = 0; i<=20; i++)
{
WebElement btn = driver.findElement(By.id("submitButton"));//Locating element
by id
if (btn.isEnabled())
{
//if webelement's attribute found enabled then this code will be executed.
System.out.print("\nCongr8s... Button is enabled and webdriver is clicking on
it now");
//Locating button by id and then clicking on it.
driver.findElement(By.id("submitButton")).click();
i=20;
}
else
{
//if webelement's attribute found disabled then this code will be executed.
System.out.print("\nSorry but Button is disabled right now..");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Page 15 of 87

6. Selenium WebDriver Tutorials - Basic Action Commands And Operations With


Examples
I have already posted Selenium WebDrier Tutorials posts how to setup web driver with
eclipse and Run first test with webdriver, how to configure junit with eclipse to generate
webdriver test report. We have also learn different methods of locating elements in webdriver. All
these things are very basic things and you need to learn all of them before starting your test case
creation in selenium 2. Now we are ready to learn next step of performing basic actions in web driver
with java for your software web application.
VIEW STEP BY STEP TUTORIALS ON SELENIUM WEBDRIVER
Today I wants to describe you few basic webdriver commands to perform actions on web element of
your web page. We can perform too many command operations in webdriver and will look about
them one by one in near future. Right now I am describing you few of them for your kind
information.
1. Creating New Instance Of Firefox Driver
WebDriver driver = new FirefoxDriver();

Above given syntax will create new instance of Firefox driver. VIEW PRACTICAL EXAMPLE
2. Command To Open URL In Browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");

This syntax will open specified URL in web browser. VIEW PRACTICAL EXAMPLE OF OPEN
URL
3. Clicking on any element or button of webpage
driver.findElement(By.id("submitButton")).click();

Above given syntax will click on targeted element in webdriver. VIEW PRACTICAL EXAMPLE
OF CLICK ON ELEMENT
4. Store text of targeted element in variable
String dropdown = driver.findElement(By.tagName("select")).getText();

This syntax will retrieve text from targeted element and will store it in variable = dropdown. VIEW
PRACTICAL EXAMPLE OF Get Text
5. Typing text in text box or text area.
driver.findElement(By.name("fname")).sendKeys("My First Name");

Above syntax will type specified text in targeted element. VIEW PRACTICAL EXAMPLE OF
SendKeys
6. Applying Implicit wait in webdriver
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

This syntax will force webdriver to wait for 15 second if element not found on page. VIEW
PRACTICAL EXAMPLE OF IMPLICIT WAIT

Page 16 of 87

7. Applying Explicit wait in webdriver with WebDriver canned conditions.


WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@id
='timeLeft']"), "Time left: 7 seconds"));

Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7 seconds" to be appear on
targeted element. VIWE DIFFERENT PRACTICAL EXAMPLES OF EXPLICIT WAIT
8. Get page title in selenium webdriver
driver.getTitle();

It will retrieve page title and you can store it in variable to use in next steps. VIEW PRACTICAL EXAMPLE
OF GET TITLE

9. Get Current Page URL In Selenium WebDriver


driver.getCurrentUrl();

It will retrieve current page URL and you can use it to compare with your expected URL. VIEW
PRACTICAL EXAMPLE OF GET CURRENT URL

10. Get domain name using java script executor


JavascriptExecutor javascript = (JavascriptExecutor) driver;
String CurrentURLUsingJS=(String)javascript.executeScript("return
document.domain");

Above syntax will retrieve your software application's domain name using webdriver's java script
executor interface and store it in to variable. VIEW GET DOMAIN NAME PRACTICAL EXAMPLE.
11. Generate alert using webdriver's java script executor interface
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");

It will generate alert during your selenium webdriver test case execution. VIEW PRACTICAL EXAMPLE
OF GENERATE ALERT USING SELENIUM WEBDRIVER.
12. Selecting or Deselecting value from drop down in selenium webdriver.

Select By Visible Text

Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));


mydrpdwn.selectByVisibleText("Audi");

It will select value from drop down list using visible text value = "Audi".

Select By Value

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");

It will select value by value = "Italy".

Select By Index

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);

It will select value by index= 0(First option).


VIEW PRACTICAL EXAMPLES OF SELECTING VALUE FROM DROP DOWN LIST .

Deselect by Visible Text


Page 17 of 87

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");

It will deselect option by visible text = Russia from list box.

Deselect by Value

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");

It will deselect option by value = Mexico from list box.

Deselect by Index

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);

It will deselect option by Index = 5 from list box.

Deselect All

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();

It will remove all selections from list box.


VIEW PRACTICAL EXAMPLES OF DESELECT SPECIFIC OPTION FROM LIST BOX

isMultiple()

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();

It will return true if select box is multiselect else it will return false.VIEW PRACTICAL EXAMPLE
OF isMultiple()

13. Navigate to URL or Back or Forward in Selenium Webdriver


driver.navigate().to("http://only-testingblog.blogspot.in/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();

1st command will navigate to specific URL, 2nd will navigate one step back and 3rd command will
navigate one step forward. VIEW PRACTICAL EXAMPLES OF NAVIGATION COMMANDS.
14. Verify Element Present in Selenium WebDriver
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;

It will return true if element is present on page, else it will return false in variable iselementpresent.
VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT PRESENT.
15. Capturing entire page screenshot in Selenium WebDriver
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));

It will capture page screenshot and store it in your D: drive. VIEW PRACTICAL EXAMPLE ON THIS PAGE.
16. Generating Mouse Hover Event In WebDriver
Page 18 of 87

Actions actions = new Actions(driver);


WebElement moveonmenu = driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform();

Above example will move mouse on targeted element. VIEW PRACTICAL EXAMPLE OF MOUSE HOVER.
17. Handling Multiple Windows In Selenium WebDriver.
1. Get All Window Handles.
Set<String> AllWindowHandles = driver.getWindowHandles();

2. Extract parent and child window handle from all window handles.
String window1 = (String) AllWindowHandles.toArray()[0];
String window2 = (String) AllWindowHandles.toArray()[1];

3. Use window handle to switch from one window to other window.


driver.switchTo().window(window2);

Above given steps with helps you to get window handle and then how to switch from one window to
another window. VIEW PRACTICAL EXAMPLE OF HANDLING MULTIPLE WINDOWS IN WEBDRIVER
18. Check Whether Element is Enabled Or Disabled In Selenium Web driver.
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);

Above syntax will verify that element (text box) fname is enabled or not. You can use it for any input
element. VIEW PRACTICAL EXAMPLE OF VERIFY ELEMENT IS ENABLED OR NOT.
19. Enable/Disable Textbox During Selenium Webdriver Test Case Execution.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')
[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
String toenable = "document.getElementsByName('lname')
[0].removeAttribute('disabled');";
javascript.executeScript(toenable);

It will disable fname element using setAttribute() method and enable lname element
using removeAttribute() method. VIEW PRACTICAL EXAMPLE OF ENABLE/DISABLE TEXTBOX.
20. Selenium WebDriver Assertions With TestNG Framework

assertEquals

Assert.assertEquals(actual, expected);

assertEquals assertion helps you to assert actual and expected equal values. VIEW PRACTICAL EXAMPLE OF
assertEquals ASSERTION

assertNotEquals

Assert.assertNotEquals(actual, expected);

assertNotEquals assertion is useful to assert not equal values. VIEW PRACTICAL EXAMPLE OF assertNotEquals
ASSERTION.

assertTrue

Assert.assertTrue(condition);

Page 19 of 87

assertTrue assertion works for boolean value true assertion. VIEW PRACTICAL EXAMPLE OF assertTrue
ASSERTION.

assertFalse

Assert.assertFalse(condition);

assertFalse assertion works for boolean value false assertion. VIEW PRACTICAL EXAMPLE OF assertFalse
ASSERTION.
21. Submit() method to submit form
driver.findElement(By.xpath("//input[@name='Company']")).submit();

It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT FORM.


22. Handling Alert, Confirmation and Prompts Popups

String myalert = driver.switchTo().alert().getText();

To store alert text. VIEW PRACTICAL EXAMPLE OF STORE ALERT TEXT

driver.switchTo().alert().accept();

To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT

driver.switchTo().alert().dismiss();

To dismiss confirmation. VIEW PRACTICAL EXAMPLE OF CANCEL CONFIRMATION

driver.switchTo().alert().sendKeys("This Is John");

To type text In text box of prompt popup. VIEW PRACTICAL EXAMPLE OF TYPE TEXT IN PROMPT TEXT BOX

7. Web Driver Featutes


How to use implicit & explicit wait in selenium webdriver and why
There are 2 types of waits available in Webdriver/Selenium 2. One of them is implicit
wait and another one is explicit wait. Both (Implicit wait and explicit wait) are useful for
waiting in WebDriver. Using waits, we are telling WebDriver to wait for a certain amount
of time before going to next step. We will see about explicit
wait in my upcoming posts. In this post let me tell you why and how to use implicit
wait in webdriver.
Why Need Implicit Wait In WebDriver
As you knows sometimes, some elements takes some time to appear on page when
browser is loading the page. In this case, sometime your webdriver test will fail if you
have not applied Implicit wait in your test case. If implicit wait is applied in your test
case then webdriver will wait for specified amount of time if targeted element not
appears on page. As you know, we can Set default timeout or use "setTimeout"
command in selenium IDE which is same as implicit wait in webdriver.
If you write implicit wait statement in you webdriver script then it will be
applied automatically to all elements of your test case. I am suggesting you to use
Implicit wait in your all test script of software web application with 10 to 15 seconds. In
webdriver, Implicit wait statement is as bellow.
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

Page 20 of 87

Above statement will tell webdriver to wait for 15 seconds if targeted element not
found/not appears on page. Le we look at simple exemple to understand implicit wait
better.
Copy bellow given @Test method part and replace it with the @Test method part of
example given on this page. (Note : @Test method is marked with pink color in that
example).
@Test
public void test ()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
driver.findElement(By.xpath("//input[@name='namexyz']"));
}

In
Above
webdriver
test
case
with
JUnit
example,
1st
Element
'xpath("//input[@name='fname']")'
will
be
found
on
page
but
element
xpath("//input[@name='namexyz']") is not there on page. So in this case webdriver will
wait for 15 to locate that element on page because we have written implicit wait
statement
in
our
code.
At
last
webdriver
test
will
fail
because
xpath("//input[@name='namexyz']") is not on the page.
Implicit wait will be applied to all elements of test case by default
while explicit will be applied to targeted element only. This is the difference
between implicit wait and explicit wait.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitButton"
)));

wait for text to be present with example using explicit wait


WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@id
='timeLeft']"), "Time left: 7 seconds"));

wait for alert in selenium 2


WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());

How to wait till element visible or appear or present on page

In any software web application's webdriver test case, you can easily wait for presence of element
using IMPLICIT WAIT. If you have used implicit wait in your test case then you do not require to
write any extra conditional statement to wait for element visibility. But in some cases, if
any element is taking too much
time to be visible on page then you can use EXPLICIT WAIT condition in your test case.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='t
ext3']")));

Page 21 of 87

Here above syntax will wait till 15 seconds to become targeted element(#submitButton)
clickable if it is not clickable or not loaded on the page of software web application. As
soon as targeted element becomes clickable, webdriver will go for perform next action.

Difference Between findElement and findElements with example


We have seen many examples of webdriver's findElement() in my previous posts. You will find
syntax of findElement() with example on THIS PAGE if you wants to use it in your software web
application test case. Selenium WebDriver has one more related command findElements. Now main
question
is
what
is
the
difference between findElement and findElements methods in selenium 2? First of all let me provide
you difference description and then example.
findElement() method

We need to use findElement method frequently in our webdriver test case because this is the
only way to locate any element in webdriver.

findElement method is useful to locating targeted single element.

If targeted element is not found on the page then it will throw NoSuchElementException.

findElements() method

We are using findElements method just occasionally.

findElements method will return list of all the matching elements from current page as per
given element locator mechanism.

If not found any element on current page as per given element locator mechanism, it will
return empty list.

Now let me provide you simple practical example of findElement method and findElements method
to show you clear difference. You can VIEW ALL PRACTICAL EXAMPLES OF SELENIUM
WEBDRIVER one by one.
Copy bellow given @Test method part of findElement and findElements method examples and
replace it with the @Test method part of example given on THIS PAGE. (Note : @Test method is
marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
WebElement option = driver.findElement(By.xpath("//option[@id='country5']"));
System.out.print(option.getAttribute("id")+" - "+option.getText());
List<WebElement> options= driver.findElements(By.xpath("//option"));
System.out.println(options.size());
for(int i=0;i<=options.size();i++)
{
String str = options.get(i).getAttribute("id")+" - "+options.get(i).getText();
System.out.println(str);
}
}

In above example, findElement will locate only targeted element and then print its id and text in console
while findElements will locate all those elements of current page which are under given xpath = //option.
for loop is used to print all those element's id and text in console.
Page 22 of 87

Same way you can locate all input elements, link elements etc.. using findElements method.

How To Generate And Insert Log In Selenium Webdriver Using log4j Jar
Assume you have prepared test case for your software web application test scenario (using selenium
webdriver with eclipse and junit) and now you wants generate log file to insert your execution time log
messages in to it. How you will do it? Selenium webdriver do not have any built in function or method to
generate log file. In this case you can use apache logging service. Let me describe you steps to generate
log
file
in
selenium
webdriver.
Steps To Generate And Insert Log In Selenium Webdriver
1. Download log4j jar file from logging.apache.org

Click Here to go to log4j jar file downloading page. (This Link URL may change in future).

Click on Zip folder link as shown in bellow image. Current version of log4j jar file is log4j1.2.17. Version of log4j jar file may be different in future due to the frequent version change.

When you click on zip folder link, it will show you zip mirror links to download folder.
Download and save zip folder by clicking on mirror link.

Now Extract that zip folder and look inside that extracted folder. You will find log4j-1.2.17.jar file
in it.

2. Import log4j-1.2.17.jar file in your eclipse project from

Right click on your project folder and go to Build Path -> Configure Build path. It will open java
build path window as shown in bellow image.

Click on Add External JARs button and select log4j-1.2.17.jar file. It will add log4j-1.2.17.jar file
in your build path.
Page 23 of 87

Click on OK button to close java build path window.

3. Create Properties folder under your project folder and add log4j.properties file in it.

Create folder with name = Properties under your project by right clicking on your project folder.

Click Here to download log4j.properties file and save it in Properties folder which is created
under your project folder.

Now your properties folder under project folder will looks like bellow.

4. Set Run Configuration


This is optional step. You need to set your Run configure if log file is not generated and display bellow
given warning message in your console when you run your test case.
log4j:WARN No appenders could be found for logger (dao.hsqlmanager).

Go to Run -> Run Configurations -> Classpath

Select User Entries -> Click on 'Advanced' button -> Select Add Folder -> And then select
Properties folder from your project and click on OK. Now your Class tab will looks like bellow.

5. Create example(Sample) test case under your project.


Create your own test case or copy example test case from here and paste it in your class file.
6. Import log4j header file in your project
Import bellow given header file in your test case class file.
import org.apache.log4j.*;

7. Replace bellow given syntax in your class file and Run your test case.

Page 24 of 87

@Test
public void test () throws InterruptedException
{
Logger log;
driver.findElement(By.id("text1")).sendKeys("My First Name");
log = Logger.getLogger(Mytesting.class);
log.info("Type In Text field.");
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
log = Logger.getLogger(Mytesting.class);
log.info("Select value from drop down.");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
}

When your test case is executed, Go to folder = C:\Logs. log.log file will be created over there. Open that
file and look in to it. Log written in your test case will be inserted in your log file. In above example,
Syntax marked with Pink color are written for inserting log. Now you can write log at any place in your
test case as shown in above example.
Creating Object Repository Using Properties File In Selenium WebDriver
In selenium WebDriver, There Is not any built In facility to create object repository. So
maintenance of page objects(Page element locators) becomes very hard If you will write all
objects of page on code level. Let me give you one simple example - You have one search
button and you have used It(Using Id locator) In many
of your test cases. Now supposing someone has changed Its Id In your application then
what you will do? You will go for replacing Id of that element In all test cases wherever It Is
used? It will create overhead for you. Simple solution to remove this overhead Is creating
object repository using properties File support of java. In properties file, First we can write
element locator of web element and then we can use It In our test cases.

Let us try to create object repository for simple calculator application given on THIS PAGE
and then will try to create test case for that calc application using object repository..

How to create new properties file


To create new properties file, Right click on your project package -> New -> Other .

Page 25 of 87

It will open New wizard. Expand General folder In New wizard and select File and click
on Next button.

Give file name objects.properties on next window and click on Finish button.

Page 26 of 87

It will add object.properties file under your package. Now copy paste bellow given lines in
objects.properties file. So now this objects.properties file Is object repository for your web
application page calc.

objects.properties file
#Created unique key for Id of all web elements.
# Example 'one' Is key and '1' Is ID of web element button 1.
one=1
two=2
three=3
four=4
five=5
six=6
seven=7
eight=8
nine=9
zero=0
equalsto=equals
cler=AC
result=Resultbox
plus=plus
minus=minus
mul=multiply

In above file, Left side value Is key and right side value Is element locator(by Id) of all web
elements of web calculator. You can use other element locator methods too like xpath, css
ect.. VISIT THIS LINK to view different element locator methods of webdriver.

Now let us create webdriver test case to perform some operations on calculation. In bellow
given example, All the element locators are coming from objects.properties file
using obj.getProperty(key). Here key Is reference of element locator value in
objects.properties file.

Page 27 of 87

package ObjectRepo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterMethod;
org.testng.annotations.BeforeMethod;
org.testng.annotations.Test;

public class CalcTest {


WebDriver driver = new FirefoxDriver();
@BeforeMethod
public void openbrowser() throws IOException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}
@AfterMethod
public void closebrowser() {
driver.quit();
}
@Test
public void Calc_Operations() throws IOException{
//Create Object of Properties Class.
Properties obj = new Properties();
//Create Object of FileInputStream Class. Pass file path.
FileInputStream objfile = new FileInputStream(System.getProperty("user.dir")
+"\\src\\ObjectRepo\\objects.properties");
//Pass object reference objfile to load method of Properties object.
obj.load(objfile);
//Sum operation on calculator.
//Accessing element locators of all web elements using obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("eight"))).click();
driver.findElement(By.id(obj.getProperty("plus"))).click();
driver.findElement(By.id(obj.getProperty("four"))).click();
driver.findElement(By.id(obj.getProperty("equalsto"))).click();
String i =
driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");
System.out.println(obj.getProperty("eight")+" + "+obj.getProperty("four")+" =
"+i);
driver.findElement(By.id(obj.getProperty("result"))).clear();
//Subtraction operation on calculator.
//Accessing element locators of all web elements using obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("nine"))).click();
driver.findElement(By.id(obj.getProperty("minus"))).click();
driver.findElement(By.id(obj.getProperty("three"))).click();
driver.findElement(By.id(obj.getProperty("equalsto"))).click();
String j =
driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");

Page 28 of 87

System.out.println(obj.getProperty("nine")+" - "+obj.getProperty("three")+" =
"+j);
}
}

Run above given example In your eclipse and observe execution.

Now supposing I have many such test cases and some one has changed Id of any button of
calc application then what I have to do? I have to modify all test cases? Answer Is No. I just
need to modify objects.properties file because I have not use element's Id directly In any
test case but I have Used just Its key reference In all test cases.

This way you can create object repository of all your web elements In one .properties file.
You can VIEW MORE TUTORIALS about selenium webdriver.

How To Get/Extract All Links From Web Page Using Selenium WebDriver
As we all knows, Each and every software web application contains many number of
different links/URLs. Some of them are redirecting to some page of same website and
others are redirecting to any external website. One of my blog reader has requested the
webdriver test script example for printing all these links in
console. I have created and published many different WEBDRIVER EXAMPLE SCRIPTS on
this blog but requested example by blog reader is not pushed till now so I have created
example for the same to share with all of you.
You can look at example of EXTRACTING TABLE DATA USING SELENIUM WEBDRIVER.

We have seen HOW TO USE findElements in webdriver to locate multiple elements of


page. We can use same thing here to locate multiple links of the page. Bellow given
example will retrieve all URLs from the page and will print all of them in console. You can
click on each URL if you wish to do so. Try bellow given example for different websites by
providing that website's URL in @Before annotation.

Copy bellow given @Test method part of extract all links from web page and replace it with
the @Test method part of example given on THIS PAGE.(Note : @Test method is marked
with pink color in that linked page).

@Test
public void test () throws InterruptedException
{
try {
List<WebElement> no = driver.findElements(By.tagName("a"));
int nooflinks = no.size();
System.out.println(nooflinks);
for (WebElement pagelink : no)
{
String linktext = pagelink.getText();
String link = pagelink.getAttribute("href");

Page 29 of 87

System.out.println(linktext+" ->");
System.out.println(link);
}
}catch (Exception e){
System.out.println("error "+e);
}
}

How To Extract Table Data/Read Table Data Using Selenium WebDriver Example
Table Is very frequently used element In web pages. Many times you need to extract your
web table data to compare and verify as per your test case. You can read about How To
Extracting All Links From Page If you need It In your test scenarios. If you knows,
Selenium IDE has also many commands related to Table
and you can view all of them on LINK 1 and LINK 2 with examples. Now let me come to
our current discussion point about how to read values from table. Before reading values
from web table, You must know there are how many rows and how many columns In your
table. Let we try to get number of rows and columns from table.

SELENIUM WEBDRIVER STEP BY STEP TUTORIALS.


How To Get Number Of Rows Using Selenium WebDriver

Look at the firebug view of above HTML table. In any web table, Number of <tr> tags Inside
<tbody> tag describes the number of rows of table. So you need to calculate that there are
how many <tr> tags Inside <tbody> tag. To get row count for above given example table,
we can use webdriver statement like bellow.

int Row_count = driver.findElements(By.xpath("//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr")).size();

In above syntax, .size() method with webdriver's findElements method will retrieve the
count of <tr> tags and store It In Row_count variable.

Page 30 of 87

How To Get Number Of Columns Using Selenium WebDriver

Same way In any web table, Number of <td> tags from any <tr> tag describes the number
of columns of table as shown In bellow given Image.

So for getting number of columns, we can use syntax like bellow.

int Col_count = driver.findElements(By.xpath("//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();

Now we have row count and column count. One more thing you require to read data from
table Is generating Xpath for each cell of column. Look at bellow given xpath syntax of 1st
cell's 1st and 2nd rows.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[2]/td[1]
Highlighted string Is common for both cell's xpath. Only changing Is row number Inside tr
node. So here we can pass Row_count variable's value Inside tr node.
Same way, look at bellow given xpath syntax of 1st and 2nd cells of 1st row. Highlighted
string Is common for both cell's xpath. Only changing Is column number Inside td node. So
here we can pass Col_count variable's value Inside td node.
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[2]
All above thing Is applied In bellow given example. Simply run It In your eclipse using
testng and observe output In console.
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

Page 31 of 87

import
import
import
import

org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class table {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/09/test.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void print_data(){
//Get number of rows In table.
int Row_count = driver.findElements(By.xpath("//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr")).size();
System.out.println("Number Of Rows = "+Row_count);
//Get number of columns In table.
int Col_count = driver.findElements(By.xpath("//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();
System.out.println("Number Of Columns = "+Col_count);
//divided xpath In three parts to pass Row_count and Col_count values.
String first_part = "//*[@id='post-body6522850981930750493']/div[1]/table/tbody/tr[";
String second_part = "]/td[";
String third_part = "]";
//Used for loop for number of rows.
for (int i=1; i<=Row_count; i++){
//Used for loop for number of columns.
for(int j=1; j<=Col_count; j++){
//Prepared final xpath of specific cell as per values of i and j.
String final_xpath = first_part+i+second_part+j+third_part;
//Will retrieve value from located cell and print It.
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.print(Table_data +" ");
}
System.out.println("");
System.out.println("");
}
}
}

Console output of above given example will looks like bellow.

Page 32 of 87

Number Of Rows = 3
Number Of Columns = 6
11 12 13 14 15 16
21

22

23

24

25

26

31

32

33

34

35

36

Here you can see, all the values of table are extracted and printed.

How To Handle Dynamic Web Table In Selenium WebDriver


If web table has same number of rows and same number of cells In each rows every time
you load page then It Is very easy to handle that table's data In selenium WebDriver as
described In How To Extract Table Data/Read Table Data Using Selenium WebDriver
post.
Now
supposing
your
table's
rows
and
columns are increasing/decreasing every time you loading page or some rows has more
cells and some rows has less cells then you need to put some extra code In your webdriver
test case which can retrieve cell data based on number of cells In specific row. Consider the
table shown In bellow given Image.

In this table, Row number 1, 2 and 4 has 3 cells, Row number 3 has 2 Cells and Row 5 has 1
cell. In this case, You need to do some extra code to handle these dynamic cells of different
rows. To do It, You need to find out the number of cells of that specific row before retrieving
data from It.

You can view more webdriver tutorials with testng and java WEBDRIVER TUTORIAL
@PART 1 and WEBDRIVER TUTORIAL @PART 2.

Bellow given example will first locate the row and then It will calculate the cells from that
row and then based on number of cells, It will retrieve cell data Information.

Run bellow given example In your eclipse with testng which Is designed for above given
dynamic web table.
package Testng_Pack;
import java.util.List;
import java.util.concurrent.TimeUnit;
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;

Page 33 of 87

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class dynamic_table {
WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void Handle_Dynamic_Webtable() {
//To locate table.
WebElement mytable = driver.findElement(By.xpath(".//*[@id='post-body8228718889842861683']/div[1]/table/tbody"));
//To locate rows of table.
List<WebElement> rows_table = mytable.findElements(By.tagName("tr"));
//To calculate no of rows In table.
int rows_count = rows_table.size();
//Loop will execute till the last row of table.
for (int row=0; row<rows_count; row++){
//To locate columns(cells) of that specific row.
List<WebElement> Columns_row =
rows_table.get(row).findElements(By.tagName("td"));
//To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row "+row+" are "+columns_count);
//Loop will execute till the last cell of that specific row.
for (int column=0; column<columns_count; column++){
//To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number "+row+" and column number
"+column+" Is "+celtext);
}
System.out.println("--------------------------------------------------");
}
}
}

Above example will works for dynamic changing web table too where number of rows
changing every time you load the page or search for something.

How To Create And Use Custom Firefox Profile For Selenium WebDriver
Page 34 of 87

What Is the Firefox Profile?


When you Install Firefox In your computer, Firefox creates one default profile folder In your local drive
to save your preferences like your bookmarks, your preferred home page on Firefox open, your toolbar
settings, your saved passwords and all the other settings. You can create different profiles for your
Firefox
browser as per your requirement. Now supposing same computer Is used by two users and both wants
their own Firefox settings then both users can create their own Firefox profile to access their own settings
when he/she opens Firefox browser.
You can LEARN SELENIUM WEBDRIVER STEP BY STEP to become master of selenium
Webdriver.
If you have noticed, When you will run your selenium webdriver test In Firefox browser then WebDriver
will open blank Firefox browser like No bookmarks, No saved passwords, No addons etc.. as shown In
bellow given Image.

If you wants access of all these things In your selenium webdriver test browser then you have to create
new profile of Firefox and set all required properties In newly created profile and then you can access
that profile In webdriver using FirefoxProfile class of webdriver.
First Of all, Let us see how to create new profile of Firefox and then we will see how to use that profile
In your test.
How to Create New Custom Firefox Profile For Selenium WebDriver?
To create new firefox profile manually,

Close Firefox browser from File -> Exit.

Go to Start -> Run and type "firefox.exe -p" In run window and click OK. It will open "Firefox Choose User Profile" dialogue as shown In bellow Image.

Page 35 of 87

Now click on Create profile button. It will open create profile wizard dialogue. Click On Next as
shown In bellow given Image.

On next screen, Give profile name = "WebDriver_Profile" and click on finish button as shown In
bellow given Image.

It Will create new profile of Firefox.

To use that newly Created profile, Select that profile and click on Start Firefox button as shown In
bellow given Image. It will open Firefox browser with newly created profile.

Now you can make you required settings on this new created profile browser like add your
required addons, bookmark your required page, network settings, proxy settings, etc.. and all other
required settings.

Page 36 of 87

How To Access Custom Firefox(Changing User Agent) Profile In Selenium WebDriver Test
To access newly created Firefox profile In selenium WebDriver, We needs to use webdriver's Inbuilt
class ProfilesIni and Its method getProfile as shown In bellow given example.
package Testng_Pack;
import
import
import
import
import
import
import

org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.firefox.FirefoxProfile;
org.openqa.selenium.firefox.internal.ProfilesIni;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class custom_profile {


WebDriver driver;
@BeforeTest
public void StartBrowser() {
//Create object of webdriver's inbuilt class ProfilesIni to access Its method
getProfile.
ProfilesIni firProfiles = new ProfilesIni();
//Get access of newly created profile WebDriver_Profile.
FirefoxProfile wbdrverprofile = firProfiles.getProfile("WebDriver_Profile");
//Pass wbdrverprofile parameter to FirefoxDriver.
driver = new FirefoxDriver(wbdrverprofile);
}
@Test
public void OpenURL(){
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}

When you will run above given example, It will open Firefox browser with newly created profile
settings.
Why needs To Set Firefox Profile In Selenium WebDriver
To perform some actions In your selenium webdriver test, You need special Firefox profile. Some
example actions are as bellow where we need to set Firefox profile. We will learn more about how to
perform all those actions In Selenium webdriver In my upcoming posts.
1. To Download files. VIEW EXAMPLE
2. To Set Proxy Settings.
3. To Resolve Certificate related errors.
If you have any example where we need to set Firefox profile properties then you can share It with world
by commenting bellow.

How To Download Different Files Using Selenium WebDriver


In my PREVIOUS POST, we have learnt about how to create create and use custom profile Firefox
browser to use It In selenium webdriver. Now let me show you how to create Firefox custom profile run
Page 37 of 87

time and set Its properties to download any file using selenium webdriver. Many times you need to
download
different files from sites like MS Excel file, MS Word File, Zip file, PDF file, CSV file, Text file, ect..
It Is tricky way to download file using selenium webdriver. Manually when you click on link to
download file, It will show you dialogue to save file In your local drive as shown In bellow given Image.

Now selenium webdriver do not have any feature to handle this save file dialogue. But yes, Selenium
webdriver has one more very good feature by which you do not need to handle that dialogue and you can
download any file very easily. We can do It using webdriver's Inbuilt class FirefoxProfile and Its different
methods. Before looking at example of downloading file, Let me describe you some thing about file's
MIME types. Yes you must know MIME type of file which you wants to download using selenium
webdriver.
What Is MIME of File
MIME Is full form of Multi-purpose Internet Mail Extensions which Is useful to Identify file type by
browser or server to transfer online.
You need to provide MIME type of file In your selenium webdriver test so that you must be aware about
It. There are many online tools available to know MIME type of any file. Just google with "MIME
checker" to find this kind of tools.
In our example given bellow, I have used MIME types as shown bellow for different file types In bellow
given selenium webdriver test.
1. Text File (.txt) - text/plain
2. PDF File (.pdf) - application/pdf
3. CSV File (.csv) - text/csv
4. MS Excel File (.xlsx) - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
5. MS
word
File
(.docx)
officedocument.wordprocessingml.document

- application/vnd.openxmlformats-

Example Of downloading different files using selenium webdriver

package Testng_Pack;
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.firefox.FirefoxProfile;
org.testng.annotations.AfterTest;

Page 38 of 87

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class downloadingfile {
WebDriver driver;
@BeforeTest
public void StartBrowser() {
//Create object of FirefoxProfile in built class to access Its properties.
FirefoxProfile fprofile = new FirefoxProfile();
//Set Location to store files after downloading.
fprofile.setPreference("browser.download.dir", "D:\\WebDriverdownloads");
fprofile.setPreference("browser.download.folderList", 2);
//Set Preference to not show file download confirmation dialogue using MIME types
Of different file extension types.
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"//MIME types
Of MS Excel File.
+ "application/pdf;" //MIME types Of PDF File.
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document;"
//MIME types Of MS doc File.
+ "text/plain;" //MIME types Of text File.
+ "text/csv"); //MIME types Of CSV File.
fprofile.setPreference( "browser.download.manager.showWhenStarting", false );
fprofile.setPreference( "pdfjs.disabled", true );
//Pass fprofile parameter In webdriver to use preferences to download file.
driver = new FirefoxDriver(fprofile);
}
@Test
public void OpenURL() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//Download Text File
driver.findElement(By.xpath("//a[contains(.,'Download Text File')]")).click();
Thread.sleep(5000);//To wait till file gets downloaded.
//Download PDF File
driver.findElement(By.xpath("//a[contains(.,'Download PDF File')]")).click();
Thread.sleep(5000);
//Download CSV File
driver.findElement(By.xpath("//a[contains(.,'Download CSV File')]")).click();
Thread.sleep(5000);
//Download Excel File
driver.findElement(By.xpath("//a[contains(.,'Download Excel File')]")).click();
Thread.sleep(5000);
//Download Doc File
driver.findElement(By.xpath("//a[contains(.,'Download Doc File')]")).click();
Thread.sleep(5000);
}
@AfterTest
public void CloseBrowser() {
driver.quit();
}
}

When you run above example, It will download all 5(Text, pdf, CSV, docx and xlsx) files one by one and
store them In D:\WebDriverdownloads folder automatically as shown In bellow given example.
Page 39 of 87

InterruptedException Is used with method OpenURL to handle checked exception of Thread.sleep(5000).


View detailed tutorials of exception handling In selenium WebDriver on THIS LINK.
This way you can download any file using selenium webdriver like zip file, exe file, etc.. Just know your
file's MIME type and download It as shown In above example.

How To Handle Ajax Auto Suggest Drop List In Selenium Webdriver


What Is Ajax Auto Suggest Drop List?
Before learning about how to handle ajax auto suggest drop list In selenium webdriver, Let
me tell you what Is ajax auto suggest drop list. If you have visited any site with search box
and that search box Is showing auto suggest list when you type some thing Inside It.
Simplest example of ajax auto suggest drop list Id
Google search suggestion. When you will type something Inside It, It will show you a list of
suggestions as shown In bellow given Image.

This Is only example for your reference. You will find this kind of ajax drop lists In many
sites.

How to handle ajax drop list In selenium WebDriver


Now supposing you wants to select some value from that auto suggest list or you wants to
store and print all those suggestions then how will you do It?. If you know, It Is very hard to
handle such ajax In selenium IDE. Let we try to print all those suggestions In console.

Here, Xpath pattern Is same for all ajax auto suggest drop list Items. Only changing Is Value
Inside <tr> tag. See bellow xpath of 1st two Items of drop list.

Page 40 of 87

//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr[1]/td/div/table/tbody/tr[1]/td[1]/span
//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr[2]/td/div/table/tbody/tr[1]/td[1]/span

So we will use for loop(As described In my THIS POST) to feed that changing values to
xpath of drop list different Items. Other one thing we need to consider Is we don't know
how many Items It will show In ajax drop list. Some keywords show you 4 Items and some
other will show you more than 4 Items In drop list. To handle this dynamic changing list, We
will USE TRY CATCH BLOCK to catch the NoSuchElementException exception if not found
next Item In ajax drop list.

In bellow given example, we have used testng @DataProvider annotation. If you know,
@DataProvider annotation Is useful for data driven testing. THIS LINKED POST will
describe you the usage of @DataProvider annotation with detailed example and
explanation.

Run bellow given example In your eclipse with testng and see how It Is retrieving values
from ajax drop list and print them In console.

package Testng_Pack;
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class Ajax_Handle {


WebDriver driver = new FirefoxDriver();

@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://www.google.com");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
//Data provider Is used for supplying 2 different values to Search_Test
method.
@DataProvider(name="search-data")
public Object[][] dataProviderTest(){
return new Object[][]{{"selenium webdriver tutorial"},{"auto s"}};
}

Page 41 of 87

@Test(dataProvider="search-data")
public void Search_Test(String Search){
driver.findElement(By.xpath("//input[@id='gbqfq']")).clear();
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys(Search);
int i=1;
int j=i+1;
try{
//for loop will run till the NoSuchElementException
exception.
for(i=1; i<j;i++)
{
//Value of variable i Is used for creating
xpath of drop list's different elements.
String suggestion =
driver.findElement(By.xpath("//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr["
+i+"]/td/div/table/tbody/tr/td[1]/span")).getText();
System.out.println(suggestion);
j++;
}
}catch(Exception e){//Catch block will catch and
handle the exception.
System.out.println("***Please search for another
word***");
System.out.println();
}
}
}

This way you can also select specific from that suggestion for your searching purpose. It Is
very simple In selenium webdriver. You can use other or more search values In above
example. To do It simply modify @DataProvider annotation method.

Introduction Of TestNG - Unit Testing Framework For Selenium WebDriver


TestNG is unit testing framework and it has been most popular in very sort time among java developers
and selenium webdriver automation test engineers. I can say, TestNG has not only most of all the features
of JUnit but also many more advanced features in terms of selenium webdriver testing framework.
Basically,
TestNG's development is inspired from combination of NUnit and JUnit. You can VIEW JUNIT WITH
WEBDRIVER TUTORIALS AND EXAMPLES before going to learn TestNG framework. There are
many new features in TestNG which makes it more powerful, stronger and easier to use. VIEW
SIMILARITIES AND DIFFERENCES between TestNG and JUnit.
TestNG Major Features

TestNG has a built in multiple Before and After and other annotations like @BeforeSuite,
@AfterSuite, @BeforeTest, @BeforeGroups, @DataProvider, @Parameters, @Test etc.. All
the TestNG annotations are very easy to understand and implement. We will look each and every
annotation with detailed description in my latter posts.

We can configure dependent test methods in TestNG means TestTwo() is dependent to TestOne().
We can also configure that if earlier test method (TestOne()) fails during execution then
dependent test method(TestTwo()) has to be executed or not.
Page 42 of 87

There is not required to extend any class in TestNG.

We can configure our test suite using test methods, classes, packages, groups, etc.. in single
testng.xml file.

Support of configuring test groups like backendtest-group, frontendtest-group etc.. and we can tell
TestNG to execute only specific group/groups.

TestNG is supported by many tools and plug-ins like Eclipse, Maven, IDEA, etc..

TestNG support parallel testing, Parameterization (Passing parameters values through XML
configuration), Data Driven Testing(executing same test method multiple times using different
data) .

TestNG has built in HTML report and XML report generation facility. It has also built in logging
facility.

VIEW

MORE

TESTNG

TUTORIALS

All these are major features of TestNG and some of them are available in JUnit too. I recommend you to
use TestNG framework with WebDriver test because there are many useful features available in it
compared to JUnit. Read my latter posts to learn TestNG framework with its detailed features.
Steps Of Downloading And Installing Testng In Eclipse For WebDriver
To use TestNG Framework in Eclipse, First of all we have to install it. Installation of TestNG in
Eclipse is very easy process. As I described in my PREVIOUS POST, TestNG is very
powerful and easy to use framework and it is supported by tools like Eclipse, Maven, IDEA,
etc..
Here
we
are
going
to
use
TestNG
Framework with Eclipse so obviously you must have installed latest Java development kit
(JDK) in your system and you must have Eclipse. CLICK HERE to view steps of downloading
JDK and Eclipse.

Once you have installed JDK and Eclipse in your system, You are ready to install TestNG in
Eclipse. Bellow given steps will describe you how to install TestNG in Eclipse.
TestNG Installation Steps In Eclipse
Step 1 : Open Eclipse and go to Menu Help -> Install New Software.

It will open new software installation window as shown in bellow given image.
Page 43 of 87

Step 2 : In new software installation window, Type URL = http://beust.com/eclipse


exactly in Work with field and click on Add button as shown in bellow given image.

It will show you option TestNG with check box. Select that check box and click on Next
Button as shown in above image.
When you click on Next button, it will check for requirements and dependency first.

When it completes requirement and dependency test, click on Next button. On Next screen,
it will ask you to accept TestNg terms and license agreement. Accept it and click on Finish
button as shown in bellow given image.

Page 44 of 87

TestNG will take few minutes to finish its installation when you click on finish button.
Step 3 : Now you need to verify that TestNG is installed in your eclipse or not.
To verify Go to Eclipse's Menu Window -> Show View -> Others as shown in bellow
given image.

It will open Show View window. Expand java folder as shown in bellow given image and
verify that TestNG is available inside it or not. If it is there means TestNG is installed
successfully in eclipse.

Page 45 of 87

What Are The Similarities/Difference Between Junit and TestNG Framework For
WebDriver
As you know, JUnit and TestNG are very popular unit testing frameworks for java developers and we can
use them in our webdriver test execution. Till now, I have described all WEBDRIVER
TUTORIALS with junit framework. Many peoples are asking me to describe the similarities and
difference between JUnit and
TestNG Framework. First of all let me give you few similarities of JUnit and TestNG frameworks and
then I will tell you difference between both of them.
(Note : Bellow given similarities and differences are based on JUnit 4 version.)
Similarities Between JUnit and TestNG
1. We can create test suite in JUnit and TestNG both frameworks.
2. Timeout Test Is possible very easily in both the frameworks.
3. We can ignore specific test case execution from suite in both the frameworks.
4. It is possible to create expected exception test in both the frameworks.
5. Annotations - Few annotations are similar in both frameworks suite like @Test, @BeforeClass,
@AfterClass. JUnit's Annotations @Before and @After are similar to TestNG's @BeforeMethod
and @AfterMethod annotations.
Difference Between JUnit and TestNG
1. In TestNG, Parameterized test configuration is very easy while It is very hard to configure
Parameterized test in JUnit.
2. TestNG support group test but it is not supported in JUnit.
3. TestNG has a feature to configure dependency test. Dependency test configuration is not possible
in JUnit.
4. TestNG support @BeforeTest, @AfterTest, @BeforeSuite, @AfterSuite, @BeforeGroups,
@AfterGroups which are not supported in JUnit.

Page 46 of 87

5. Test prioritization, Parallel testing is possible in TestNG. It is not supported by JUnit.


6. View more features of TestNG @ THIS LINK .
If you knows more differences or features then you can post it by commenting bellow.

How To Create And Run First TestNG-WebDriver Test Case In Eclipse


Our next step to do is - TestNG test case creation in eclipse after installation of TestNG in eclipse. You
can VIEW TESTNG INSTALLATION STEPS in my earlier post if you have not configured TestNG in
your eclipse. Now let me describe you steps of writing your first test case with TestNG.
Step 1 : Create New Project And Package
First of all, Create new java project in your eclipse with name = "TestNGOne" and create package
"TestNGOnePack" under your project. VISIT THIS POST If you don't know how to create new java
project and package in eclipse.
Step 2 : Add TestNG Library
For adding TestNG library,

Go to your project's Properties -> Java Build Path -> Libraries Tab.

Click on Add Library button -> Select TestNG from Add Library popup and then click on Next
and Finish buttons.

It will add TestNg library in your project as shown in bellow image. Now click on OK button to close
that window.

Page 47 of 87

Step 3 : Create TestNG Class


To add TestNg class

Right click on package "TestNGOnePack" -> New -> Other. It will open New wizard window as
bellow.

Select TestNg from New wizard window and click on Next button.

On next screen, add class name = ClassOne

Page 48 of 87

It will add new class (ClassOne) under package as shown in bellow given image.

Step 4 : Add webdriver's external jar file in your project.


To Run webdriver test, you need to add webdriver's jar files as external jar file in your project. VIEW
THIS POST to know how to download webdriver jar files and add external jar file to java build path.
(Note : Do not add junit jar file as external jar file. Now its not required in TestNG framework).
This is it. Now you are ready to write your webdriver test script inside your class.
Step 5 : Add/write sample webdriver test script.
Write your own test script or add bellow given script in your class file.

package TestNGOnePack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ClassOne {
WebDriver driver = new FirefoxDriver();
//@BeforeMethod defines this method has to run before every @Test methods
@BeforeMethod
public void openbrowser() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
//@AfterMethod defines this method has to run after every @Test methods
@AfterMethod
public void closebrowser() {
System.out.print("\nBrowser close");
driver.quit();
}
@Test
public void testmethodone() {
String title = driver.getTitle();
System.out.print("Current page title is : "+title);

Page 49 of 87

System.out.print("\n'TestNGOne -> TestNGOnePack -> ClassOne -> testmethodone' has


been executed successfully");
}
}

Step 6 : Run Webdriver test script with TestNG


Go to Run -> Run As -> And Click on TestNg Test as shown in bellow given image.

It will run your webdriver test with TestNG. When execution completed, You will see result as shown in
bellow given image.

Step 7 : View test execution HTML report generated by TestNG


To view test execution report,

Right click on "TestNGOne" project folder in eclipse and select Refresh.

Folder with name = "test-output" will be created under your project folder as shown in bellow
given Image.

Page 50 of 87

Explore that folder and open it with web Browser as shown in above image. It will open report in
eclipse as shown in bellow given image.

TestNG Annotations With Selenium WebDriver Examples


As you know, TestNG is the framework which is very useful to use with selenium WebDriver.
I have shared all selenium webdriver with testng tutorials on THIS LINK. The main reason
behind TestNG's popularity is we can create and configure test case and test suite very
easily
using
many
different
annotations
of
TestNG.
Few annotations are similar in TestNG and junit and you can view junit annotations with
example on this JUNIT ANNOTATIONS POST.

Annotations are those things in TestNG which guides it for what to do next or which method
should be executed next. TestNG has also facility to pass parameters with annotations. Let
we look at TestNG annotations list with its functional description.

@Test
@Test annotation describes method as a test method or part of your test.

testng.xml : Creating Single Or Multiple Tests For Multiple Classes In WebDriver


As i have described in my previous post, We can configure our webdriver test or webdriver test suits in
testng.xml file. In my PREVIOUS POST, we have seen how to create testng.xml file to run single test
class. Also If you don't know how to create and run first TestNG-WebDriver test, You can VIEW THIS
POST.
Now supposing you have two/multiple classes in your test suite then how will you run them? We can run
both the classes in same test as well in 2 different tests too.
Page 51 of 87

First of all, Create 3 classes under project = TestNGOne and package = TestNGOnePack as bellow.

"BaseClassOne" will be used for initializing and closing webdriver instance,

"ClassOne" and "ClassTwo" will be used as test classes.

VIEW ALL WEBDRIVER-TESTNG TUTORIAL POSTS


1. BaseClassOne.java
package TestNGOnePack;
import java.util.concurrent.TimeUnit;
import
import
import
import

org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterSuite;
org.testng.annotations.BeforeSuite;

public class BaseClassOne {


//Declared as public static to use same webdriver instance publicly
public static WebDriver driver = new FirefoxDriver();
//@BeforeSuite annotation describes this method has to run before all suites
@BeforeSuite
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
//@AfterSuite annotation describes this method has to run after execution of all
suites
@AfterSuite
public void tearDown() throws Exception {
driver.quit();
}
}

Above class will be used as base class to initialize and close webdriver instance.
2. ClassOne.java
package TestNGOnePack;
import org.testng.annotations.Test;
public class ClassOne extends TestNGOnePack.BaseClassOne{
//@Test annotation describes this method as a test method
@Test
public void testmethodone() {
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been
executed successfully");

Page 52 of 87

}
}

Above ClassOne is inherited from BaseClassOne.


3. ClassTwo.java
package TestNGOnePack;
import org.testng.annotations.Test;
public class ClassTwo extends TestNGOnePack.BaseClassOne{
//@Test annotation describes this method as a test method
@Test
public void testmethodone() {
driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been
executed successfully");
}
}

Above ClassTwo is also inherited from BaseClassOne.


Now your class structure will be looks like bellow in eclipse.

Configure testng.xml to run two classes in one test


Now let me show you how to configure testng.xml to run both classes in single test. Copy-paste bellow
given lines in your testng.xml file and then Run it as TestNg Suite. Here, both classes are included in
single test (Test One).
<suite name="Suite One" >
<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
<class name="TestNGOnePack.ClassTwo" />
</classes>
</test>
</suite>

When execution completed, View execution result reports. It will looks like bellow.

Page 53 of 87

Configure testng.xml to run two classes in two tests


Now if you wants to run both classes as separate test then you have to configure your testng.xml file as
bellow.
<suite name="Suite One" >
<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
</classes>
</test>
<test name="Test Two" >
<classes>
<class name="TestNGOnePack.ClassTwo" />
</classes>
</test>
</suite>

Here, "ClassOne" is included in 'Test One" test and "ClassTwo" is included in 'Test Two" test. Now run
bellow given testng.xml file and verify result.

Now compare both the results. In 1st example, Both classes are executed under same test but in 2nd
example both classes are executed under separate tests. This way you can configure testng.xml file as per
your requirement.
@BeforeMethod
Page 54 of 87

Any method which is marked with @BeforeMethod annotation will be executed before each and every
@test annotated method.

@AfterMethod
Same as @BeforeMethod, If any method is annotated with @AfterMethod annotation then it will be
executed after execution of each and every @test annotated method.
@BeforeClass
Method annotated using @BeforeClass will be executed before first @Test method execution.
@BeforeClass annotated method will be executed once only per class so don't be confused.
@AfterClass
Same as @BeforeClass, Method annotated with @AfterClass annotation will be executed once only per
class after execution of all @Test annotated methods of that class.
@BeforeTest
@BeforeTest annotated method will be executed before the any @Test annotated method of those classes
which are inside <test> tag in testng.xml file.
@AfterTest
@AfterTest annotated method will be executed when all @Test annotated methods completes its
execution of those classes which are inside <test> tag in testng.xml file.
@BeforeSuite
Method marked with @BeforeSuite annotation will run before the all suites from test.
@AfterSuite
@AfterSuite annotated method will start running when execution of all tests executed from current test
suite.
@DataProvider
When you use @DataProvider annotation for any method that means you are using that method as a data
supplier. Configuration of @DataProvider annotated method must be like it always return Object[][]
which we can use in @Test annotated method.
WebDriver Test Data Driven Testing Using TestNG @DataProvider Annotation
Data driven testing Is most Important topic for all software testing automation tools
because you need to provide different set of data In your tests. If you are selenium IDE user
and you wants to perform data driven testing IN YOUR TEST then THESE POSTS will helps
you. For Selenium Webdriver, Data driven testing
using excel file Is very easy. For that you need support of Java Excel API and It Is explained
very clearly In THIS POST. Now If you are using TestNG framework for selenium webdriver
then there Is one another way to perform data driven testing.

TestNG @DataProvider Annotation


@DataProvider Is TestNG annotation. @DataProvider Annotation of testng framework
provides us a facility of storing and preparing data set In method. Task of @DataProvider
annotated method Is supplying data for a test method. Means you can configure data set In
that method and then use that data In your test method. @DataProvider annotated method
must return an Object[][] with data.

Page 55 of 87

Let us see simple example of data driven testing using @DataProvider annotation. We have
to create 2 dimensional array In @DataProvider annotated method to store data as shown
In bellow given example. You can VIEW THIS POST to know more about two dimensional
array In java.
Bellow given example will retrieve userid and password one by one from @DataProvider
annotated method and will feed them In LogIn_Test(String Usedid, String Pass) one by one.
Run this example In your eclipse and observe result.

package Testng_Pack;
import
import
import
import
import
import
import
import

java.util.concurrent.TimeUnit;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.DataProvider;
org.testng.annotations.Test;

public class Sample_Login {


WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
//This method will return two dimensional array.
//This method behaves as data provider for LogIn_Test method.
@DataProvider
public Object[][] LoginCredentials(){
//Created two dimensional array with 4 rows and 2 columns.
//4 rows represents test has to run 4 times.
//2 columns represents 2 data parameters.
Object[][] Cred = new Object[4][2];
Cred[0][0] = "UserId1";
Cred[0][1] = "Pass1";
Cred[1][0] = "UserId2";
Cred[1][1] = "Pass2";
Cred[2][0] = "UserId3";
Cred[2][1] = "Pass3";

Page 56 of 87

Cred[3][0] = "UserId4";
Cred[3][1] = "Pass4";
return Cred; //Returned Cred
}
//Give data provider method name as data provider.
//Passed 2 string parameters as LoginCredentials() returns 2 parameters In object.
@Test(dataProvider="LoginCredentials")
public void LogIn_Test(String Usedid, String Pass){
driver.findElement(By.xpath("//input[@name='userid']")).clear();
driver.findElement(By.xpath("//input[@name='pswrd']")).clear();
driver.findElement(By.xpath("//input[@name='userid']")).sendKeys(Usedid);
driver.findElement(By.xpath("//input[@name='pswrd']")).sendKeys(Pass);
driver.findElement(By.xpath("//input[@value='Login']")).click();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}

testng.xml file to run this example Is as bellow.

<suite name="Simple Suite">


<test name="Simple Skip Test">
<classes>
<class name = "Testng_Pack.Sample_Login"/>
</classes>
</test>
</suite>

When you will run above example In eclipse, It will enter UserID and passwords one by one
In UserId and password test box of web page. TestNG result report will looks like bellow.

@BeforeGroups
@BeforeGroups annotated method will run before the first test run of that specific group.
@AfterGroups
@AfterGroups annotated method will run after all test methods of that group completes its execution.

Page 57 of 87

@Parameters
When you wants to pass parameters in your test methods, you need to use @Parameters annotation.
Selenium WebDriver Parallel Tests Execution Using TestNG - @Parameters
Browser compatibility testing Is most Important thing for any web application and generally
you have to perform browser compatibility testing before 1 or 2 days of final release of
application. In such a sort time period, you have to verify each Important functionality In
every browsers suggested by client. If you will go
for running your all webdriver tests In each browsers one by one then It will take too much
time to complete your test and you may not complete It before release. In such situation,
Running your tests In all required browsers at same time will helps you to save your time
efforts. So question Is - Can we run our tests parallel In all required browsers using
webdriver? Answer Is yes.

Before learning how to run webdriver test parallel in multiple browsers, You must have
knowledge about how to run test In webdriver using TestNg framework. You will find links of
TestNG tutorial post with examples on THIS PAGE. I have described testng configuration
with detailed explanation on those links so read them carefully one by one. You can read
webdriver related more tutorials on THIS LINK.

Parallelism In TestNG
You can configure your testng.xml file In such a way to run your test suite or tests or
methods In seperate browsers Is known as parallelism In TestNG. Interviewer can ask you
this question. Now let us look at example of parellel test execution In webdriver using
testng. Bellow given example will run the test In Mozilla Firefox and Google chrome browser
parallel.

Created Test_Parallel.java class file for testing application and configured testng.xml file to
run tests parallel as shown In bellow given example. In testng.xml file, parallel="tests"
Inside <suite> tag will Instruct TestNG to consider bunch of methods of each <test> tag as
separate thread. Means If you wants to run your test In 2 different browsers then you need
to create two <test> blocks for each browser Inside testng.xml file and Inside each <test>
tag block, define one more tag "parameter" with same name(In both <test> block) but with
different values. In bellow given testng.xml file, each <test> block has "parameter" tag
with same name = browser but different values(FFX and CRM).

In testcase, I have used @Parameters annotation to pass parameter In method. Values of


this parameter will be feed by testng.xml file. and then If condition will check that value to
decide which driver to use for test. This way, example testng.xml file will feed two
values(FFX and CRM) In parameter so It will open Firefox and Google chrome browsers and
run test In both browsers. (For running test In google chrome, You need to download
chromedriver.exe. VIEW THIS POST to know more how to run webdriver test In google
chrome browser).

Run bellow given test In your eclipse with testng to see how It runs your test In 2 browsers
at same time.

Page 58 of 87

Test_Parallel.java

package Testng_Pack;
import org.junit.Assert;
public class Test_Parallel {
private WebDriver driver=null;
@BeforeClass
//parameter value will retrieved from testng.xml file's <parameter> tag.
@Parameters ({"browser"})
public void setup(String browser){//Method will pass value of parameter.
if (browser.equals("FFX")) {//If value Is FFX then webdriver will open Firefox
Browser.
System.out.println("Test Starts Running In Firefox Browser.");
driver = new FirefoxDriver();
}else if (browser.equals("CRM")){//If value Is CRM then webdriver will open chrome
Browser.
System.out.println("Test Starts Running In Google chrome.");
System.setProperty("webdriver.chrome.driver",
"D:\\chromedriver_win32_2.3\\chromedriver.exe");
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}
//Both bellow given tests will be executed In both browsers.
@Test
public void verify_title(){
String title = driver.getTitle();
Assert.assertEquals("Only Testing: LogIn", title);
System.out.println("Title Is Fine.");
}
@Test
public void verify_message(){
driver.findElement(By.xpath("//input[@name='userid']")).sendKeys("UID1");
driver.findElement(By.xpath("//input[@type='password']")).sendKeys("pass1");
driver.findElement(By.xpath("//input[@value='Login']")).click();
String alert = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
Assert.assertEquals("UserId Is : UID1 Password Is : pass1", alert);
System.out.println("Alert Is Fine.");
}
@AfterClass
public void closebrowser(){
driver.quit();
}
}

testng.xml

<suite name="webDriver" parallel="tests">


<test name="Test In FireFox" >
<parameter name="browser" value="FFX" />
<classes>

Page 59 of 87

<class name="Testng_Pack.Test_Parallel" />


</classes>
</test>
<test name="Test In Google Chrome" >
<parameter name="browser" value="CRM"></parameter>
<classes>
<class name="Testng_Pack.Test_Parallel"></class>
</classes>
</test>
</suite>

If you wants to run your test In one more browser then you need to create new <test> tag
block in testng.xml file and set another parameter value and then put one more if else
condition in class file to check and run your test.

This way you can your test parallel In multiple browsers at same time to reduce your time
efforts.

@Factory
When you wants to execute specific group of test cases with different values, you need to use @Factory
annotation. An array of class objects is returned by @Factory annotated method and those TestNG will
those objects as test classes.
@Listeners
@Listeners are used to with test class. It is helpful for logging purpose.
How To Ignore Test In WebDriver With JUnit
As described in my PREVIOUS POST, We can create junit test suite to execute multiple
test cases from one place. See example of my previous post. junittest2 class have
two @Test methods. Now If I wants to exclude/Ignore 1st @Test method from execution and
wants to execute only 2nd @Test method then how
can I do It? Ignoring specific test in junit test is very easy.

@Ignore annotation
We can use JUnit's has inbuilt @Ignore annotation before @Test method to Ignore that
specific webdriver test from execution. Let we apply @Ignore annotation practically in our
test and then observe its execution result.
VIEW JUNIT EXAMPLE OF TIMEOUT AND EXPECTED EXCEPTION TEST
My scenario is to ignore 1st @Test method from execution so i need to put @Ignore
annotation in my test before 1st @Test method as bellow.

@Ignore
@Test
public void test1() throws InterruptedException{
}

Here, @Ignore annotation will exclude test1() method from execution.


Page 60 of 87

Copy bellow given Ignoring @Test method(test1()) part with @Ignore annotation and
replace it will @Test method part given on Step 3 (Create 2nd test case) of THIS
EXAMPLE (Note : @Test method part which needs to replace is marked with pink color in
that example post).

//To ignore this @Test method from execution


@Ignore
@Test
public void test1() throws InterruptedException{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("junittest2 classtest1");
System.out.print("\njunittest2 class-test1 method is executed");
Thread.sleep(2000);
}

Now when you run full test suite(junittestsuite.java) then on completion of junit test suite
execution, you will get bellow given result in console.
junittest1 class is executed
junittest2 class-test2 method is executed
As per console result, ignored test(test1()) is not executed.
JUnit test execution report will looks like bellow.

This way, Junit's @Ignore annotation will help us to ignore specific test from execution.

Creating And Running WebDriver Test Suit Using testng.xml File


Introduction Of testng.xml File
In TestNG framework, We need to create testng.xml file to create and handle multiple test classes.
testng.xml is the file where we can configure our webdriver test, set test dependency, include or exclude
any test method or class or package, set priority etc.. We will learn each and every thing about TestNG
usage in
my future posts. Right now let me describe you how to create testng.xml
Creating testng.xml File

First of all Create a project and webdriver test case as described in my PREVIOUS POST.

To create testng.xml file, Right click on project folder and Go to New -> File as shown in bellow
given image. It will open New File wizard.

Page 61 of 87

In New file wizard, select "TestNGOne" project and add file name = "testng.xml" as shown in
bellow given image and click on Finish button.

It will add testng.xml file under your project folder. Now add bellow given lines in your
testng.xml file.

<suite name="Suite One" >


<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
</classes>
</test>
</suite>

Now your testng.xml file will looks like bellow.


Page 62 of 87

In above testng.xml code,

<suite> : suite tag defines the TestNG suite. You can give any name to your suite using 'name'
attribute. In above given example, We have given "Suite One" to our test suite.

<test> : test tag defines the TestNG test. You can give any name to your test using 'name'
attribute. In above given example, We have given "Test One" to our test.

<classes> : classes tag defines multiple class. We can multiple test class under classes tag. In our
example we have only one class.

<class> : class tag defines the class name which you wants to consider in test execution. In
above given example, we have defined name="TestNGOnePack.ClassOne" where
'TestNGOnePack' describes package name and 'ClassOne' describes class name.

This way, above given testng.xml file will execute only ClassOne class from TestNGOnePack package.
Executing testng.xml File
To Run
Right click on testng.xml file -> Run As -> Select TestNG Suite as shown in bellow given image.

It will start execution of defined test class 'ClassOne' from 'TestNGOnePack' package.
Page 63 of 87

When execution completed, You can view test execution HTML report as described in my PREVIOUS
POST. Test execution HTML report will looks like bellow.

This is the one simple example of creating and running testng.xml file in eclipse for webdriver. We will
see different examples of testng.xml file to configure our test in my future post.

testng.xml : Creating WebDriver Test Suite Using Classes From Different Packages
Now you are already aware about HOW TO CREATE testng.xml FILE to configure and run
your webdriver test. The main reason behind popularity of TestNG framework for webdriver
is we can configure our test as per our requirements. I have listed
some Similarities/Differences between Junit and TestNG
framework In THIS POST. In my previous post, We have already seen example of how to
configure testng.xml file to run single/multiple webdriver test classes of same package.
Now let me show you an example of how to create test suite using classes from different
packages.

First of all let we create new packages and classes as described in bellow given 3 steps.

Step
1.
Create
package
=
"TestNGOnePack"
= BaseClassOne.java, ClassOne.java and ClassTwo.java exactly as
PREVIOUS POST.

with
described

classes
in my

Step 2. Create package = "TestNGTwoPack" under same project and add ClassOne.java
and ClassTwo.java files with bellow given code lines.
ClassOne.java
package TestNGTwoPack;
import org.testng.annotations.Test;
public class ClassOne extends TestNGOnePack.BaseClassOne{
@Test
public void testmethodone() {
String title = driver.getTitle();

Page 64 of 87

System.out.print("\nCurrent page title is : "+title);


String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been
executed successfully");
}
}

ClassTwo.java
package TestNGTwoPack;
import org.testng.annotations.Test;
public class ClassTwo extends TestNGOnePack.BaseClassOne{
@Test
public void testmethodone() {
driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been
executed successfully");
}
}

Above given both classes are inherited from TestNGOnePack.BaseClassOne to use


webdriver instance, initialization and closing the webdriver.

Step 3. Create package = "TestNGThreePack" under same project and add ClassOne.java
and ClassTwo.java files with above given code lines. You need to change package name in
both class(TestNGTwoPack to TestNGThreePack) to use them in "TestNGThreePack" package.

So now, my package and class hierarchy is as bellow for project TestNgOne.

Now supposing I do not want to execute all class of all packages and I wants to execute
only
few
of
them
Page 65 of 87

like TestNGOnePack.ClassOne, TestNGTwoPack.ClassTwo, TestNGThreePack.ClassOne


and TestNGThreePack.ClassTwo. How can we do that? You need to configure your testng.xml
file as bellow.
<suite name="Suite One">
<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
<class name="TestNGTwoPack.ClassTwo" />
<class name="TestNGThreePack.ClassOne" />
<class name="TestNGThreePack.ClassTwo" />
</classes>
</test>
</suite>

Above given file will run only described 4 classes out of total 6 classes under single test
(Test One). You can divide them in multiple tests too as described in my previous post.

Now execute above given testng.xml file and verify result. It will looks like as shown in
bellow given image.

This way we can configure our test suite using only specific class from different packages.

Configure testng.xml In Eclipse For Selenium WebDriver To Run All Or Specific


Package
TestNG is very useful and powerful framework for selenium webdriver. We need to configure our tests
based on our requirements or test scenarios. We are going very slowly with TestNG framework to
understand each and everything clearly with examples so that it can help you to configure your test in any
king of situations. In my previous posts, we have learnt about HOW TO RUN SPECIFIC CLASS
FROM DIFFERENT PACKAGE USING testng.xml and HOW TO RUN SINGLE OR MULTIPLE
CLASSES FROM ONE PACKAGE USING testng.xml. So now you can configure your testng.xml
file to run any specific class from any package if you have read both previous posts.
Configure TestNGOne Project In Eclipse
In testng.xml file, You can also configure to run specific package or all packages of project. Let we see
both examples. First of all, Create bellow given three packages with required classes, methods and code
same as described in my PREVIOUS POST.
Page 66 of 87

1. TestNGOnePack(package) -> BaseClassOne.java, ClassOne.java, ClassTwo.java


2. TestNGTwoPack(package) -> ClassOne.java, ClassTwo.java
3. TestNGThreePack(package) -> ClassOne.java, ClassTwo.java
So now your project structure should be as shown in bellow given image.

Configure testng.xml to run selected packages from all packages of webdriver project in single test
suite
From three packages, I wants to run only two packages -> "TestNGTwoPack" and "TestNGThreePack".
For that we need to configure testng.xml as bellow.
<suite name="Suite One">
<test name="Test One" >
<packages>
<package name="TestNGTwoPack" />
<package name="TestNGThreePack" />
</packages>
</test>
</suite>

In above given testng.xml code, <packages> tag packages is used to describe group of packages
and <package> tag package is used to add specific package in our test suite. So when you run above
testng.xml file, It will run only targeted two packages(TestNGTwoPack, TestNGThreePack). Other
(TestNGOnePack)package(s) will be excluded from execution. Execution report will looks like bellow.

Page 67 of 87

As you see, "TestNGOnePack" package is not executed as shown in above report image.
Configure testng.xml to run all packages of project in single test suite
If you wants to run all packages of your project, you can configure your testng.xml using wildcard(.*)
with package tag as bellow.

<suite name="Suite One">


<test name="Test One" >
<packages>
<package name=".*" />
</packages>
</test>
</suite>

Above given testng.xml file will execute all packages of your selenium webdriver project and test result
report will looks like bellow.

As you see in report, Now all the packages are executed. This way, we can use wild card to include all
webdriver test packages in our test.

Page 68 of 87

Include/Exclude Only Selected Test Methods In Selenium WebDriver-TestNg Test Suite


Using testng.xml
If you are using selenium webdriver with TestNg framework then you can easily run your selected test
methods from selected classes. Supposing you have a two classes in your package and first class have
three test methods and second class have five test methods. Now you wants to run only one test method
from first
class and two test methods from second class then you can configure it very easily in testng.xml file. Let
me show you how to do it with simple webdriver test configured by testng.xml file.
Configure TestNGOne Project In Eclipse
1. First of all, Configure TestNGOne project in eclipse as described in PREVIOUS POST.
2. Add testmethodtwo() bellow the testmethodone() as shown bellow in ClassOne.java
and ClassTwo.java file of all three packages.
public class ClassTwo extends TestNGOnePack.BaseClassOne{
@Test
public void testmethodone() {
driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
String title = driver.getTitle();
System.out.print("\nCurrent page title is : "+title);
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been
executed successfully");
}
//Add testmethodtwo() here
@Test
public void testmethodtwo() {
driver.findElement(By.xpath("//input[@value='female']"));
String Workdir = System.getProperty("user.dir");
String Classpackname = this.getClass().getName();
System.out.print("\n'"+Workdir+" -> "+Classpackname+" -> testmethodtwo' has
been executed successfully");
}
}

Now your TestNGOne project's structure will looks like bellow.

Page 69 of 87

Configure testng.xml file to Include and run selected webdriver test methods from few classes
Now supposing, I wants to run only

testmethodone() method from TestNGOnePack -> ClassOne.java

testmethodone() and testmethodtwo() methods from TestNGTwoPack -> ClassTwo.java

testmethodone() and testmethodtwo() methods from TestNGThreePack -> ClassOne.java

testmethodone() and testmethodtwo() methods from TestNGThreePack -> ClassTwo.java

To perform above action, I have to configure my testng.xml file as bellow.

<suite name="Suite One">


<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
<methods>
<include name="testmethodone" />
</methods>
<class name="TestNGTwoPack.ClassTwo" />
</classes>
<packages>

Page 70 of 87

<package name="TestNGThreePack" />


</packages>
</test>
</suite>

In above given testng.xml file, methods and include tags are new to learn. You can read about TestNg
Framework's <suite>, <test>, <classes> and <class> tags in THIS POST and <packages>, <package>
tags in THIS POST. <methods> tag defines the group of methods and <include> tag defines which
method you wants to include in execution. Now execute this testng.xml file and verify the result report.

If you see in above result, Only test testmethodone() is executed from TestNGOnePack -> ClassOne.java.
This way we can include any specific method in our test suite to execute from any class.
Configure testng.xml file to exclude specific test method from class
Sameway, To exclude specific test method from class, We can use <exclude> tag inside <methods> tag as
bellow.

<suite name="Suite One">


<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne" />
<methods>
<include name="testmethodone" />
</methods>
<class name="TestNGTwoPack.ClassTwo" />
<methods>
<exclude name="testmethodone" />
</methods>
</classes>
<packages>
<package name="TestNGThreePack" />
</packages>
</test>
</suite>

When you run above given testng.xml file, it will exclude testmethodone() test method of
TestNGTwoPack -> ClassTwo.jav from execution and will execute only ClassTwo.java file as shown in
bellow given test result report.
Page 71 of 87

This way we can configure our testng.xml file to include or exclude any specific test method from
execution.

Include/Exclude Selenium WebDriver Test Package From Test Suite Using testng.xml
Now you are already aware about HOW TO INCLUDE OR EXCLUDE SELECTED TEST
METHODS IN TEST SUITE. Now our next tutorial is about how to include or exclude
selected package from execution of test suite. Supposing you have multiple packages in
your webdriver test suite and you
wants to run only specific selected package then how will you do it? Let we look at simple
example for the same.

First of all configure project "TestNGOne" with 3 packages as described in my PREVIOUS


POST.

Configuring testng.xml file to include only specific package in test suite from
multiple packages
As described in my THIS POST, we can use wildcard(.*) with package tag to run all
packages but then immediately we will use include to run specific package from all the
packages as bellow.

<suite name="Suite One">


<test name="Test One" >
<packages>
<package name=".*">
<include name="TestNGOnePack" />
</package>
</packages>
</test>
</suite>

Page 72 of 87

When you run above given testng.xml file, it will run only "TestNGOnePack" package from
all packages of "TestNGOne" project. Look at bellow given TestNg result report.

If you see in above test result of webdriver testng suite, only classes and methods of
"TestNGOnePack" package are executed. remaining 2 packages(TestNGTwoPack and
TestNGThreePack) are not executed.

Configuring testng.xml file to exclude specific package from execution


To exclude specific package from execution, You need to configure your testng.xml file as
bellow. Supposing I wants to exclude "TestNGThreePack" package from execution.
<suite name="Suite One">
<test name="Test One" >
<packages>
<package name=".*">
<exclude name="TestNGThreePack" />
</package>
</packages>
</test>
</suite>

Above given testng.xml file with exclude "TestNGThreePack" package from execution and
will execute remaining two packages as shown in bellow given report image.

Page 73 of 87

This way we can include or exclude full package from execution.

TestNg With Selenium WebDriver : Using Regular Expression To Include/Exclude Test Method
From Execution
It is very important for us to know the each and every way of testng.xml configuration to
include/exclude selected test methods or packages in execution. You can view my posts to
know how to include/exclude SELECTED PACKAGE or SELECTED TEST METHODS from
selenium webdriver test suite
execution. There is also one another way of including or excluding selected test method
using regular expression. Let me describe it with one simple example.

For that you need to configure "TestNGOne" project using 3 packages as shown in THIS
POST. Now let we configure testng.xml file.

Including/Excluding test methods using regular expression

Supposing,
I
wants
to
Include testmethodtwo()
from TestNGOnePack
-> ClassOne.java file
and
Exclude testmethodtwo()
from TestNGTwoPack
-> ClassTwo.java file using regular expression. For that my testng.xml file configuration
will be looks like bellow.

<suite name="Suite One">


<test name="Test One" >
<classes>
<class name="TestNGOnePack.ClassOne">
<methods>
<include name=".*two.*"/>
</methods>
</class>

Page 74 of 87

<class name="TestNGTwoPack.ClassTwo">
<methods>
<exclude name=".*two.*"/>
</methods>
</class>
</classes>
</test>
</suite>

If you see in above testng.xml file, ".*two.*" is regular expression used for test methods.
Means test methods containing "two" word will be considered for inclusion/exclusion in test
suite execution.. Now when I will run above testng.xml file, Selenium webdriver test
execution report will looks like bellow.

If you see in above given test execution report, only two methods has been executed as per
our expectation. This way you can use regular expressions for method's inclusion or
exclusion.

How To Skip WebDriver Test In TestNG


If you remember, I have posted many posts on TestNG Framework and you will find all
those posts on THIS LINK or you can VIEW THIS PAGE for all related posts listing. Study
all of them one by one on posted date order for your better understanding. Till now we
have
learnt
about
how
to
Include
or
exclude
TEST METHOD, PACKAGE from execution. We have also learnt REGULAR EXPRESSION
USAGE for Including or Excluding Test methods from execution. Now supposing you wants
to skip specific test Intentionally from execution then how can you do It?

Skipping WebDriver Test Intentionally


One way of skipping selenium webdriver test method Is using throw new SkipException()
exception - TestNG Exception. Sometimes you need to check some condition like If some
condition match then skip test else perform some action In your webdriver test. In this kind
of situation, you can use SkipException() exception.
Page 75 of 87

Let us look at simple webdriver test case example where I have placed SkipException()
Inside if condition to Intentionally skip that test. Please note one thing here : once
SkipException() thrown, remaining part of that test method will be not executed and control
will goes directly to next test method execution.

In bellow given example, If condition will match so throw new SkipException() part will be
executed and due to that exception, "After If Else" statement will be not
printed. Intensional_Skip() method will be displayed as skipped in Testng report.

Run bellow given example In your eclipse and observe result.

package Testng_Pack;
import
import
import
import
import
import
import
import

java.util.concurrent.TimeUnit;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.SkipException;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class Test_NG {


public static WebDriver driver = new FirefoxDriver();

@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}
@Test
public void Intensional_Skip(){
System.out.println("In Verify_Title");
String titl = driver.getTitle();
if(titl.equals("Only Testing: New Test")){
//To Skip Test
throw new SkipException("Test Check_Checkbox Is Skipped");
}else{
System.out.println("Check the Checkbox");
driver.findElement(By.xpath("//input[@value='Bike']")).click();
}
System.out.println("After If Else");
}
@Test

Page 76 of 87

public void Radio_check(){


System.out.println("In Check_Radio");
driver.findElement(By.xpath("//input[@value='male']")).click();
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
}

testng.xml CLICK HERE to view how to create testng.xml

<suite name="Simple Suite">


<test name="Simple Skip Test">
<classes>
<class name = "Testng_Pack.Test_NG"/>
</classes>
</test>
</suite>

Result will be as bellow:

Page 77 of 87

Assert.assertEquals TestNG With Selenium WebDriver Example


There are many assertions available in Selenium WebDriver with TestNG framework and we will look at
all of then one by one. Assertions are important and very useful in any automation tools to assert
something during your test execution. If you know, Selenium IDE has many built in assertion commands
and if you are
selenium IDE user then you can view set of selenium IDE assertion command examples on THIS LINK.
Difference between Assertion and verification
Verification and assertion is little different so don't be confused. Verification will just verify but assertion
will first verify and if result is not as per expectation then it will stop execution of that specific test
method. Today let we look at assertEquals assertion in selenium webdriver.
Assert.assertEquals(actual, expected) assertion
This assertion is useful to compare expected and actual values in selenium webdriver. If both values
match then its fine and will continue execution. But if fails then immediately it will mark that specific
test method as fail and exit from that test method.
You can use different types of values in actual and expected like boolean, byte[], char, double, float, int,
etc.. but function is same for all. Let we look at simple example to understand it better.
Steps :

First of all, create 3 classes (BaseClassOne.java and ClassTwo.java) as describe in THIS POST if
you don't have created.

Now copy paste bellow given lines in your ClassTwo.java file.

Assertion and Verification Example Of Selenium WebDriver With TestNg


package TestNGOnePack;
import
import
import
import

org.openqa.selenium.By;
org.testng.Assert;
org.testng.annotations.BeforeClass;
org.testng.annotations.Test;

public class ClassTwo extends TestNGOnePack.BaseClassOne{


String Actualtext;
@BeforeClass
public void load_url(){
driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
//Method Example For Assertion
@Test
public void assertion_method_1() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
Assert.assertEquals(Actualtext, "Tuesday, 28 January 2014");
System.out.print("\n assertion_method_1() -> Part executed");
}
//Method Example For Assertion
@Test
public void assertion_method_2() {
Assert.assertEquals(Actualtext, "Tuesday, 29 January 2014");
System.out.print("\n assertion_method_2() -> Part executed");
}

Page 78 of 87

//Method Example For Verification


@Test
public void verification_method() {
String time = driver.findElement(By.xpath("//div[@id='timeLeft']")).getText();
if (time == "Tuesday, 28 January 2014")
{
System.out.print("\nText Match");
}
else
{
System.out.print("\nText does Match");
}
}
}

testng.xml example to run single class


To Run above example using testng.xml file, you will have to configure it as bellow.
<suite name="Suite One" configfailurepolicy="continue">
<test name="Test One">
<classes>
<class name="TestNGOnePack.ClassTwo" />
</classes>
</test>
</suite>

If you run above example, assertion_method_1() will display pass in result but assertion_method_2() will
display fail because here expected and actual values will not match with each other.

If you will look in console, Only "assertion_method_1() -> Part executed" will be printed over there.
"assertion_method_2() -> Part executed" will be not there because execution of current method was
skipped after assertion failure. Last verification_method() is just simple verification method which
verifies text and print message based on result.

Example Of assertNotEquals In Selenium WebDriver With TestNG

Page 79 of 87

As described in my PREVIOUS POST, assertEquals assertion is useful to compare two


string, boolean, byte[], char, double, float, int, etc.. and based on assertion result, Your test
method will pass or fail. This pass or fail indication will helps you in your testing process. So
this is the very good function in selenium
WebDriver which helps us to find and log issue. Please note one thing once more is - Use
hard assertions in selenium webdriver only when you wants to skip remaining test
execution on assertion fail. If you wants to continue execution on assertion failure, you can
use TestNg soft assertions. We will discuss about it in my upcoming post.

You can VIEW SELENIUM IDE ASSERTION EXAMPLES for your reference.

Assert.assertNotEquals(actual, expected, message) assertion


Other one assertion in selenium WebDriver is assertNotEquals assertion. It's function is
opposite to assertEquals assertion. Means if both sides values will not match then this
assertion will pass else it will fail. Here you can write your own message for failure
condition. Simplest example of Assert.assertNotEquals in selenium webdriver is as bellow.

Replace bellow given test methods (assertion_method_1() and assertion_method_2()) with


example given in my PREVIOUS POST and then run it using testng.xml file.

//Assertion Method
@Test
public void assertion_method_1() {
Actualtext = driver.findElement(By.xpath("//h2/span")).getText();
Assert.assertNotEquals(Actualtext, "Tuesday, 28 January 2014", "Expected and
actual match in assertion_method_1");
System.out.print("\n assertion_method_1() -> Part executed");
}
//Assertion Method
@Test
public void assertion_method_2() {
Assert.assertNotEquals(Actualtext, "Tuesday, 29 January 2014", "Expected and
actual match in assertion_method_2");
System.out.print("\n assertion_method_2() -> Part executed");
}

You test execution result will looks like bellow..

Page 80 of 87

Here, test method assertion_method_1() will fail because actual string text and expected
string text will match. Assertion message will be printed in test result report as marked with
green color in above image.

Selenium WebDriver assertTrue assertion example with TestNG


Previously we have learnt two assertions of selenium webdriver. You can view practical
example
pages
of
selenium
webdriver
assertions
- assertEquals
and
assertNotEquals before learning assertTrue(condition) assertion. There is also one
another related assertion is assertFalse(condition) assertion but we will look
about it in my next post.

assertTrue(condition) Assertion
assertTrue assertion is generally used for boolean condition true. It will pass if condition
returns "true". If it will return false then it will fail and skip test execution from that specific
method. Syntax for assertTrue assertion is as bellow.

Assert.assertTrue(condition);

Supposing you have one check box on page. You wants to check its status like it is checked
or not. And if it is not checked then you wants to skip execution from that method and
wants to fail that method in testng report. This thing can be done very easily using
assertTrue assertion. Let we look at practical example of assertTrue assertion.

Replace bellow given variables and 3 methods with example given on my THIS POST and
then run it using testng.xml file.

Page 81 of 87

WebElement chk1, chk2;


@BeforeClass
public void load_url(){
driver.get("http://only-testing-blog.blogspot.in/2014/02/attributes.html");
chk1 = driver.findElement(By.xpath("//input[@name='option1']"));
chk2 = driver.findElement(By.xpath("//input[@name='option2']"));
}
//Assertion Method - will pass
@Test
public void asserttrue1() {
System.out.print("\n"+chk1.isSelected());
Assert.assertTrue(chk1.isSelected());
System.out.print("\n asserttrue1 - > Executed - means assertion is pass");
}
//Assertion Method - will fail
@Test
public void asserttrue2() {
System.out.print("\n"+chk2.isSelected());
Assert.assertTrue(chk2.isSelected());
System.out.print("\n asserttrue2 - > Executed - means assertion is pass");
}

When you run above example in eclipse and get result, asserttrue1() method will display
pass and method asserttrue2() will display fail as shown in bellow given image.

asserttrue1() will pass because 1st check box is checked on page so chk1.isSelected() will
return true.
asserttrue2() will fail because 2nd check box is not checked on page so chk2.isSelected()
will
return
false.
In
assertion
failure
case,
code
written
after
Assert.assertTrue(chk2.isSelected()); will be not executed. Run above example in your
eclipse and verify the results then try it for your own project.

This way, Assert.assertTrue(condition) is helps use to assert boolean condition true.

Page 82 of 87

Example Of Assert.assertFalse Assertion In Selenium WebDriver With TestNG


When you are working with selenium webdriver, you must be aware about different kind of
assertions which are available. If you have a enough knowledge about webdriver
assertions,
You
can
create
very
effective
test
cases
for
your
test
scenarios. assertEquals, assertNotEquals and assertTrue assertions are already
explained in my previous posts. Now let we try to understand assertFalse assertion for
selenium webdriver.

Assert.assertFalse(condition) Assertion
It will check boolean value returned by condition and will pass if returned value is "False". If
returned value is pass then this assertion will fail and skip execution from current test
method. Syntax for assertFalse assertion is as bellow.
Assert.assertFalse(condition);

In sort, assertFalse and assertTrue assertions are opposite to each other. When you wants
to assert "True" value - you can use assertTrue assertion. And when you wants to assert
false value - you can use assertFalse assertion in your selenium webdriver test.

Let we try to use assertFalse assertion with simple example. Supposing we have two
checkboxs on page one from them is checked and another one is not checked. Let we apply
assertFalse assertion on both of these check boxes for its checked status.

Replace bellow given example methods with example of THIS PAGE. and run it with
testng.xml as described on that post.

WebElement chk1, chk2;


@BeforeClass
public void load_url(){
driver.get("http://only-testing-blog.blogspot.in/2014/02/attributes.html");
chk1 = driver.findElement(By.xpath("//input[@name='option1']"));
chk2 = driver.findElement(By.xpath("//input[@name='option2']"));
}
//Assertion Method - will Fail
@Test
public void assertfalse1() {
System.out.print("\n"+chk1.isSelected());
Assert.assertFalse(chk1.isSelected());
}
//Assertion Method - will Pass
@Test
public void assertfalse2() {
System.out.print("\n"+chk1.isSelected());
Assert.assertFalse(chk2.isSelected());
}

Page 83 of 87

In this case, assertfalse1() method will fail because it is already checked


so chk1.isSelected() will return true value. assertfalse2() method will pass because 2nd
checkbox is not checked so it will return false value. Execution result will looks like bellow.

Selenium WebDriver Assertion assertNull Example With TestNG


Assertions are very useful to check your expected result and skip execution if assertion fails
on run time. If you are selenium IDE user, you can read all these selenium IDE ASSERTION
COMMANDS examples posts to use them in your test cases for your web application.
Before describing about assertNull command,
I recommend you all to READ OTHER WEBDRIVER ASSERTION METHOD examples for
your reference.

assertNull(object) WebDriver Assertion


assertNull(object) assertion will check and verify that object is null. It will pass if object
found null. If object found not null then it will return error message like
"java.lang.AssertionError: expected [null] but found [true]". Whenever your assertion fails,
it will mark that specific test method as fail in TestNG result.

Let me present here one simple example of assertNull assertion. We have two text boxes.
1st text box is enabled and 2nd is disabled. Now let me use assertNull assertion in my test
script to assert that textbox1 is enabled and textbox2 is disabled. Here we use
textbox's disabled attribute for this assertion.

Copy and replace bellow given test methods with example given on THIS PAGE and then
run it with testng.xml file

WebElement txt1, txt2;


@BeforeClass
public void load_url(){

Page 84 of 87

driver.get("http://only-testing-blog.blogspot.in/2014/02/attributes.html");
txt1 = driver.findElement(By.xpath("//input[@id='text1']"));
txt2 = driver.findElement(By.xpath("//input[@id='text2']"));
}
//Example Of Assertion Method - will Pass
@Test
public void null1() {
System.out.print("\n"+txt1.getAttribute("disabled"));
Assert.assertNull(txt1.getAttribute("disabled"));
}
//Example Assertion Method - will Fail
@Test
public void null2() {
System.out.print("\n"+txt2.getAttribute("disabled"));
Assert.assertNull(txt2.getAttribute("disabled"));
}

In above given example, txt1.getAttribute("disabled") object will return "null" because


there is not any disabled attribute with 1st textbox. So that assertion will pass. And method
null1() will pass too. txt2.getAttribute("disabled") object will return "true" because disabled
attribute is available with textbox2. So in this case that assertion and method null2() will
fail as shown in bellow given image.

TestNG Assertion assertNotNull With WebDriver Example


As you know, there are many assertions in TestNG and you will find most of them on THIS
PAGE. Each of these TestNG assertions are designed to fulfill different kind of conditions. I
have described mostly used all assertions with very clear examples with selenium
webdriver test. If you will see on that link, you will find
example of assertNull assertion. assertNotNull assertion works opposite to assertNull
assertion means it will assert not null condition.

TestNG Assertion assertNotNull(object) WebDriver Assertion

Page 85 of 87

assertNotNull assertion is designed to check and verify that values returned by object is not
null. Means it will be pass if returned value is not null. Else it will fail.

Best example to experiment assertNotNull assertion is assertion of enabled and disabled


text fields. Let me give you simple example where we will assert "disabled" attribute of text
box to verify is it disabled or not using assertNotNull assertion.

Copy paste bellow given code in example given on THIS PAGE and then run it using
testng.xml file.

WebElement txt1, txt2;


@BeforeClass
public void load_url(){
driver.get("http://only-testing-blog.blogspot.in/2014/02/attributes.html");
txt1 = driver.findElement(By.xpath("//input[@id='text1']"));
txt2 = driver.findElement(By.xpath("//input[@id='text2']"));
}
//Example Of Assertion Method - will Fail
@Test
public void notnull1() {
System.out.print("\n"+txt1.getAttribute("disabled"));
Assert.assertNotNull(txt1.getAttribute("disabled"));
}
//Example Of Assertion Method - will Pass
@Test
public void notnull2() {
System.out.print("\n"+txt2.getAttribute("disabled"));
Assert.assertNotNull(txt2.getAttribute("disabled"));
}

In above example, assertNotNull assertion of notnull1() method will fail because expected
was not null but textbox text1 is not disabled so returned null. assertNotNull assertion
of notnull2() will pass because expected was not null and textbox text2 is disabled so it has
return true value means not null.

Page 86 of 87

Sameway, You can use assertNotNull assertion to assert checkbox is checked or not, to
assert textbox is visible or hidden, etc..

Page 87 of 87

You might also like