Selenium Web Driver
Selenium Web Driver
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).
Selenium RC
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.
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
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
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'.
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 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
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.
Now you are ready to run your script from Run menu as shown bellow.
Script Explanation
Page 6 of 87
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
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 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, 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
Above example will type the text in text box using By Name element locating method.
Page 9 of 87
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
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.
}
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
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;
Page 13 of 87
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
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
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
It will retrieve current page URL and you can use it to compare with your expected URL. VIEW
PRACTICAL EXAMPLE OF GET CURRENT URL
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.
It will select value from drop down list using visible text value = "Audi".
Select By Value
Select By Index
Deselect by Value
Deselect by Index
Deselect All
isMultiple()
It will return true if select box is multiselect else it will return false.VIEW PRACTICAL EXAMPLE
OF isMultiple()
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
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];
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();
driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
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
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"
)));
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.
We need to use findElement method frequently in our webdriver test case because this is the
only way to locate any element in webdriver.
If targeted element is not found on the page then it will throw NoSuchElementException.
findElements() method
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.
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
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.
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.
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..
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;
Page 28 of 87
System.out.println(obj.getProperty("nine")+" - "+obj.getProperty("three")+" =
"+j);
}
}
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.
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.
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.
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
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.
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;
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.
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
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,
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.
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;
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.
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-
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
This Is only example for your reference. You will find this kind of ajax drop lists In many
sites.
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;
@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.
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
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
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
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
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.
Page 48 of 87
It will add new class (ClassOne) under package as shown in bellow given image.
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
It will run your webdriver test with TestNG. When execution completed, You will see result as shown in
bellow given image.
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.
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.
First of all, Create 3 classes under project = TestNGOne and package = TestNGOnePack as bellow.
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterSuite;
org.testng.annotations.BeforeSuite;
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
}
}
When execution completed, View execution result reports. It will looks like bellow.
Page 53 of 87
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.
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;
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);
}
}
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).
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
Page 59 of 87
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{
}
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).
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.
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> : 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
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");
}
}
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.
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
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 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.
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
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
Page 70 of 87
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.
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.
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.
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.
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
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.
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.
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.
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.
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;
@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
Page 77 of 87
First of all, create 3 classes (BaseClassOne.java and ClassTwo.java) as describe in THIS POST if
you don't have created.
org.openqa.selenium.By;
org.testng.Assert;
org.testng.annotations.BeforeClass;
org.testng.annotations.Test;
Page 78 of 87
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.
Page 79 of 87
You can VIEW SELENIUM IDE ASSERTION EXAMPLES for your reference.
//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");
}
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.
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
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.
Page 82 of 87
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.
Page 83 of 87
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
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"));
}
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.
Copy paste bellow given code in example given on THIS PAGE and then run it using
testng.xml file.
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