0% found this document useful (0 votes)
182 views41 pages

Selenium Real Time Scenarios PDF

Uploaded by

Anand Dhana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
182 views41 pages

Selenium Real Time Scenarios PDF

Uploaded by

Anand Dhana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Example One:

The main difference is the inclusion of the WebDriver API into Selenium.
I’ve put together a small example below that uses the new API to log into
two web based e-mail clients and send an e-mail.
WebDriverTestBase.java
package tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

public class WebDriverTestBase {

public static FirefoxDriver driver;


public static Wait wait;

@BeforeClass(alwaysRun = true)
protected void startWebDriver() {
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 120);
}

@AfterClass(alwaysRun = true)
protected void closeSession() {
driver.close();
}

public static void assertEquals(Object actual, Object expected) {


Assert.assertEquals(actual, expected);
}
}

VisibilityOfElementLocated.java
package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;

public class VisibilityOfElementLocated implements


ExpectedCondition {

By findCondition;

VisibilityOfElementLocated(By by) {
this.findCondition = by;
}

public Boolean apply(WebDriver driver) {


driver.findElement(this.findCondition);
return Boolean.valueOf(true);
}

WebmailTest.java
package tests;

import org.openqa.selenium.By;
import org.testng.annotations.Test;

public class WebmailTest extends WebDriverTestBase {

//variables
public static final String YAHOO_EMAIL = "[email protected]";
public static final String HOTMAIL_EMAIL = "[email protected]";
@Test(description = "Sends an e-mail from Yahoo account")
public void sendFromYahoo() {
//new message variables
String to = HOTMAIL_EMAIL;
String subject = "Test Sending Email Message From Yahoo";
String message = "This is a test e-mail from Yahoo";

//login to yahoo
driver.get("http://mail.yahoo.com/");

driver.findElement(By.id("username")).sendKeys(YAHOO_EMAIL);
driver.findElement(By.id("passwd")).sendKeys("mytestpw");
driver.findElement(By.id(".save")).click();

//create new message


driver.findElement(By.id("compose_button_label")).click();
wait.until(new
VisibilityOfElementLocated(By.xpath("id('_testTo_label')/ancestor::tr[1]//textare
a")));

//send test message

driver.findElement(By.xpath("id('_testTo_label')/ancestor::tr[1]//textarea")).sendKeys(
to);

driver.findElement(By.xpath("id('_testSubject_label')/ancestor::tr[1]//input")).sendKeys
(subject);
driver.switchTo().frame("compArea_test_");
driver.findElement(By.xpath("//div")).sendKeys(message);
driver.switchTo().defaultContent();
driver.findElement(By.id("SendMessageButton_label")).click();
//WARNING! sometimes a captcha is displayed here
wait.until(new
VisibilityOfElementLocated(By.xpath("//nobr[contains(text(), 'Message
Sent')]")));
}

@Test(description = "Sends an e-mail from Hotmail account")


public void sendFromHotmail() {
//new message variables
String to = YAHOO_EMAIL;
String subject = "Test Sending Email Message From Hotmail";
String message = "This is a test e-mail from Hotmail";

//login to hotmail
driver.get("http://mail.live.com/");

driver.findElement(By.name("login")).sendKeys(HOTMAIL_EMAIL);
driver.findElement(By.name("passwd")).sendKeys("mytestpw");
if (driver.findElement(By.name("remMe")).isSelected()) {
driver.findElement(By.name("remMe")).click();
}
driver.findElement(By.name("SI")).click();

//create new message


driver.switchTo().frame("UIFrame");
driver.findElement(By.id("NewMessage")).click();

//send test message

driver.findElement(By.id("AutoCompleteTo$InputBox")).sendKeys(to);
driver.findElement(By.id("fSubject")).sendKeys(subject);
driver.switchTo().frame("UIFrame.1");
driver.findElement(By.xpath("//body")).sendKeys(message);
driver.switchTo().frame("UIFrame");
driver.findElement(By.id("SendMessage")).click();

assertEquals(driver.findElement(By.cssSelector("h1.SmcHeaderColor")).getTex
t(), "Your message has been sent");
}

}
Example Two:
Window Handle example with selenium webdriver + using Java - The
Set Interface for selenium automation testing

package testngtest;

import java.util.Iterator;
import java.util.Set;

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

public class TestNG_WindowHandleExample_by_jasmine {

// Declare global test varialbles

WebDriver jasminedriver = new FirefoxDriver();


String Open_a_popup_window;
String Positioned_Popup;
String JavaScript_Popup_Windows;

@Test
public void f() throws InterruptedException {

// A Set is a Collection that cannot contain duplicate


elements. It models the mathematical set abstraction.

Set windowids = jasminedriver.getWindowHandles();

//iterator( )
//Returns an Iterator object for the collection which may
be used to retrieve an object
Iterator iter= windowids.iterator();
JavaScript_Popup_Windows=iter.next();

// Open first popup

jasminedriver.findElement(By.xpath("//*[@id='content']/div[3]/a")
).click();

windowids = jasminedriver.getWindowHandles();
iter= windowids.iterator();
iter.next();
Open_a_popup_window=iter.next();

System.out.println(JavaScript_Popup_Windows);
System.out.println(Open_a_popup_window);

Thread.sleep(3000L);
System.out.println();
System.out.println("Positioned_Popup");

// switch to main window to click on other popup link


jasminedriver.switchTo().window(JavaScript_Popup_Wind
ows);

// Open second popup


jasminedriver.findElement(By.xpath("//*[@id='content']/d
iv[5]/p/a")).click();

windowids = jasminedriver.getWindowHandles();
iter= windowids.iterator();
iter.next();
iter.next();
Positioned_Popup = iter.next();

System.out.println(JavaScript_Popup_Windows);
System.out.println(Open_a_popup_window);
System.out.println(Positioned_Popup);
System.out.println();
Thread.sleep(3000L);

System.out.println("Centered_Popup");
}
@BeforeMethod
public void beforeMethod() {

jasminedriver.get("http://www.quackit.com/javascript/popup_win
dows.cfm");
}

@AfterMethod
public void afterMethod() {
jasminedriver.switchTo().window(Open_a_popup_window);
jasminedriver.close();

jasminedriver.switchTo().window(Positioned_Popup);
jasminedriver.close();

jasminedriver.switchTo().window(JavaScript_Popup_Windows);

jasminedriver.quit();
}

Example Three:
In Selenium 2(WebDriver), testing popup windows involve
switching the driver to the popup window and then running the
corresponding actions. Twist recorder records actions in popup
windows as commented code.

For eg.
//Write your logic to locate the appropriate popup before using
commented actions.

//Look at - 'How do I handle popup in WebDriver' section for


more details.

//action in popup "Google".


popup.findElement(By.name("q")).sendKeys("Thoughtworks");

//action in popup "Google".


popup.findElement(By.name("btnG")).submit();"

The above code is the result of recording in the popup window


having google search page, searching for "Thoughtworks".
To get the above code working:

1) Identify the popup,


The following code identifies the popup window with title
"Google". Note that the actions tells the title of the popup
window. Add the code just before the first popup action being
commented.

String parentWindowHandle = browser.getWindowHandle(); //


save the current window handle.

WebDriver popup = null;

Iterator<String> windowIterator =
browser.getWindowHandles();

while(windowIterator.hasNext()) {

String windowHandle = windowIterator.next();


popup = browser.switchTo().window(windowHandle);

if (popup.getTitle().equals("Google") {

break;

2) Uncomment code for the same popup,


//action in popup "Google".

popup.findElement(By.name("q")).sendKeys("Thoughtworks");

//action in popup "Google".

popup.findElement(By.name("btnG")).submit();"

3) After the popup actions, switch the driver back to the parent
window,
browser.close(); // close the popup.

browser.switchTo().window(parentWindowHandle); // Switch
back to parent window.

Example Four:
Creating a test suite using Selenium 2 / Webdriver

After writing my post: HYPERLINK


"http://ncona.com/2012/02/running-selenium-2-webdriver-
tests/" \o "Running Selenium 2.0 / Webdriver tests" Running
Selenium 2.0 / Webdriver tests, I was thinking how could I make a
test suite so I could run all my functional tests with just one
command. In this post I am going to explain how I used Java
classes to do this.
This post is highly based on HYPERLINK
"http://ncona.com/2012/02/running-selenium-2-webdriver-
tests/" \o "Running Selenium 2.0 / Webdriver tests" Running
Selenium 2.0 / Webdriver tests, so if you feel you don’t
understand what I am saying, please read that post first.
Test Suite
The first thing I figured is that we need a main class that will call
all the other classes tests, so I created a main test suite file called
NconaTestSuite.java with this content:

1package com.ncona;
2
3import org.openqa.selenium.
4WebDriver;
5import org.openqa.selenium.fi
6refox.FirefoxDriver;
7import org.openqa.selenium.s
8upport.ui.Wait;
9import org.openqa.selenium.s
10upport.ui.WebDriverWait;
11
12public class NconaTestSuite
13{
14
15 public static void main( HYPE
16RLINK
17"http://www.google.com/searc
18h?hl=en&q=allinurl
19%3Astring+java.sun.com&btnI
20=I%27m%20Feeling
21%20Lucky" String[] args)
22 {
23 // Objects that are going
24to be passed to all test classes
25 WebDriver
26driver = new FirefoxDriver();
27
28Wait<WebDriver>wait = new
29WebDriverWait(driver, 30);
30
31 boolean result;
32 try
33 {
34 // Here we add all the
35test classes we want to run
36 MiscTestClass
37mtc1 = new MiscTestClass();
38 MiscTestClassTwo
39mtc2 = new MiscTestClassTw
40o();
41 MiscTestClassThree
42mtc3 = new MiscTestClassThr
43ee();
44
45 // We call the run
46method (that method runs all
47 // the tests of the
48class) for each of the classes
49 // above. If any test
fails result will be false.
result = (
mtc1.run(driver,
wait)
&& mtc2.run(driver,
wait)
&& mtc3.run(driver,
wait)
)
}
catch ( HYPERLINK
"http://www.google.com/searc
h?hl=en&q=allinurl
%3Aexception+java.sun.com
&btnI=I%27m%20Feeling
%20Lucky" Exception e)
{
e.printStackTrace();
result = false;
}
finally
{
driver.close();
}

HYPERLINK
"http://www.google.com/searc
h?hl=en&q=allinurl
%3Asystem+java.sun.com&bt
nI=I%27m%20Feeling
%20Lucky"
System.out.println("Test
" + (result ? "passed." : "failed
."));
if (!result)
{
HYPERLINK
"http://www.google.com/searc
h?hl=en&q=allinurl
%3Asystem+java.sun.com&bt
nI=I%27m%20Feeling
%20Lucky" System.exit(1);
}
}
}
Test Class
Our test classes need to have a run method that will run all the
tests it contains. Here is an example of how it could look:

1package com.ncona;
2
3import java.util.List;
4import org.openqa.selenium.B
5y;
6import org.openqa.selenium.
7WebDriver;
8import org.openqa.selenium.
9WebElement;
10import org.openqa.selenium.fi
11refox.FirefoxDriver;
12import org.openqa.selenium.s
13upport.ui.ExpectedCondition;
14import org.openqa.selenium.s
15upport.ui.Wait;
16import org.openqa.selenium.s
17upport.ui.WebDriverWait;
18
19public class MiscTestClass
20{
21 static WebDriver driver;
22
23 static Wait<WebDriver> wait
24;
25
26
27 public static boolean run(We
28bDriver driverArg,
29Wait<WebDriver> waitArg)
30 {
31 driver = driverArg;
32 wait = waitArg;
33
34 setUp();
35
36 // Run all the methods
37and return false if any fails
38 return (
39 miscMethod()
40 && miscMethod2()
41 );
42 }
43
44
private static boolean miscM
ethod()
{
// Put your tests code
here

return result
}

private static boolean miscM


ethod2()
{
// Put your tests code
here

return result
}
}
Build file
The build.xml file used for this test suite almost the same as the
one in my previous post. We just need to change the target to use
the name of our new test suite file:

1<project basedir="." name="


2Test Automation">
3
4 <property name="src.dir" va
5lue="${basedir}/java/src"/>
6
7 <property name="classes.di
8r" value="$
9{basedir}/java/classes/main"/
10>
11
12 <property name="lib.dir" val
13ue="${basedir}/lib"/>
14
15 <property name="build.dir"
16value="${basedir}/build"/>
17
18 <property name="testautom
19ation.jar" value="$
20{build.dir}/testautomation.jar
21"/>
22
23
24 <path id="testautomation.cl
25asspath">
26 <file file="$
27{testautomation.jar}"/>
28 <fileset dir="${lib.dir}">
29
30 <include name="*.jar" />
31 </fileset>
32 </path>

<target name="build" descri


ption="sets up the
environment for test
execution">
<mkdir dir="$
{classes.dir}"/>
<mkdir dir="$
{build.dir}"/>
<javac debug="true"
srcdir="${src.dir}"
destdir="$
{classes.dir}"

includeAntRuntime="false"

classpathref="testautomatio
n.classpath"/>
<jar basedir="$
{classes.dir}" jarfile="$
{testautomation.jar}"/>
</target>

<target name="run-
example" description="run
command-line example">
<!---- This is the line I
modified. Classname is now
com.ncona.${example} ---->

<java classname="com.ncon
a.${example}"
failonerror="true"

classpathref="testautomatio
n.classpath"/>
</target>
</project>
Run the suite
First we need to build the project:

1ant build
Finally to run it we would use this command:

1ant run-example
-Dexample=NconaTestSuite

Example Five:
Selenium WebDriver, Selenium Server and PageObjects by Example

HYPERLINK "http://www.hascode.com/2012/03/selenium-webdriver-selenium-
server-and-pageobjects-by-example/" http://www.hascode.com/2012/03/selenium-
webdriver-selenium-server-and-pageobjects-by-example/

Example Six:
HYPERLINK "http://seleniumforum.forumotion.net/t1031-need-
selenium-webdriver-excel-sheet-examples" Selenium
Webdriver + Excel sheet examples
Example for read/write operations from excel sheet using
selenium webdriver.

import jxl.Sheet;
import jxl.Workbook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.FileInputStream;
import java.io.IOException;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class TestData{

WebDriver driver = new ChromeDriver();

public void Login() throws InterruptedException, BiffException,


IOException
{
FileInputStream fi=new
FileInputStream("D:\\sreeworkspace\\sree.xls");
Workbook workbook = Workbook.getWorkbook(fi);

Sheet sheet = workbook.getSheet("Login");


String s=sheet.getCell(2,2).getContents();
System.out.println(s);

driver.findElement(By.id("gbqfq")).sendKeys(s);
driver.findElement(By.name("btnK")).click();

public static void main(String[] args) throws


InterruptedException, BiffException, IOException {

System.setProperty("webdriver.chrome.driver",
"D:/sreekumar/Tutorial/Selenium/chromedriver_win_18.0.995.0/
chromedriver.exe");

//Pausing here seems to make it work better, so...

TestData login = new TestData();


login.driver.get("https://www.google.com");
login.Login();
}
}
Example Seven:
Uploading Files in Remote WebDriver
March 8th, 2012 by Santiago Suarez Ordoñez
Since it’s been a while since my last Selenium tips blog post, I thought it was time
to share some Selenium love again. Today we’re covering WebDriver’s native
solution to a very common issue when doing distributed cross browser
testing: uploading files in remote servers.
As you may know, the way to address this in Selenium 1 is to place your files in an
accessible web server and use the attachFile command that points to the correct
URL. With Selenium 2, the Selenium Dev team has luckily made this a lot more
straightforward.

For those of you doing this locally, all you need to do is use
the sendKeys command totype the local path of the file in any file field. This
works like a charm in all drivers. When moving this test to a remote server (such
as, for example, our Selenium 2 Cloud), all you need to do is use the
setFileDetector method to let WebDriver know that you’re uploading files from
your local computer to a remote server instead of just typing a path. Almost
magically, the file will be base64 encoded and sent transparentlythrough the
JSONWireProtocol for you before writing the fixed remote path. This is an
excellent solution, as it lets you switch your tests from a local to remote Driver
without having to worry about changing your tests’ code.

This feature is available in all the official Selenium 2 bindings, just make sure
Selenium 2.8.0 or newer is used as this feature has been released then. Here are
some examples tests:

Java

import junit.framework.Assert;
import junit.framework.TestCase;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.*;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class TestingUploadSe2Sauce extends TestCase {


private RemoteWebDriver driver;

public void setUp() throws Exception {


DesiredCapabilities capabillities = DesiredCapabilities.firefox();
capabillities.setCapability("version", "7");
capabillities.setCapability("platform", Platform.XP);
capabillities.setCapability("selenium-version", "2.18.0");
capabillities.setCapability("name", "Remote File Upload using
Selenium 2's FileDetectors");
driver = new RemoteWebDriver(
new URL("http://<username>:<api-
key>@ondemand.saucelabs.com:80/wd/hub"),
capabillities);
driver.setFileDetector(new LocalFileDetector());
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

public void testSauce() throws Exception {


driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload");
WebElement upload = driver.findElement(By.id("myfile"));
upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg");
driver.findElement(By.id("submit")).click();
driver.findElement(By.tagName("img"));
Assert.assertEquals("darkbulb.jpg (image/jpeg)",
driver.findElement(By.tagName("p")).getText());
}

public void tearDown() throws Exception {


driver.quit();
}
}

__________________________________________________________________
________________
Example Eight:

Selenium Grid with WebDriver


I had earlier covered in my blog on how to execute your RC cases
in selenium grid. But with the commencement of Selenium-
2/Webdriver, grid setup has been changed. In the following blog I
will cover how to set-up your grid and the changes that will be
required for easy execution of cases.

Following things are required:


1. Selenium 2.xx version server jar and Java library. The latest
one can be downloaded from the link: HYPERLINK
"http://code.google.com/p/selenium/downloads/list" Selenium-2
2. Java 1.6 and above
3. TestNg jar . You can download it from the link: HYPERLINK
"http://testng.org/doc/download.html" TestNG
4. Eclipse with TestNG plugin installed(optional)
5. ChromeDriver. Can be downloaded from: HYPERLINK
"http://code.google.com/p/chromium/downloads/list"
ChromeDriver

The Test Code


Following is an example of test-class that have a test case to
search google for "testing" and verifying after clicking it on a link.
HYPERLINK "http://blog.varunin.com/2011/10/selenium-grid-with-
webdriver.html" ?
1 import
2 java.net.MalformedURLExce
3 ption;
4 import java.net.URL;
5
6 import
7 org.openqa.selenium.WebDr
8 iver;
9 import
10 org.openqa.selenium.WebDr
11 iverBackedSelenium;
12 import
13 org.openqa.selenium.remot
14 e.DesiredCapabilities;
15 import
16 org.openqa.selenium.remot
17 e.RemoteWebDriver;
18 import
19 org.testng.annotations.Af
20 terClass;
21 import
22 org.testng.annotations.Be
23 foreClass;
24 import
25 org.testng.annotations.Pa
26 rameters;
27 import
28 org.testng.annotations.Te
29 st;
30
31 import
32 com.thoughtworks.selenium
33 .Selenium;
34
35 import
36 junit.framework.Assert;
37
38 public class Google {
39 private Selenium
40 selenium;
41 @Parameters({"browser","
42 port"})
43 @BeforeClass
44 public void
45 beforeClass(String
46 browser,String port){
47 DesiredCapabilities
capability= new
48
DesiredCapabilities();
49
capability.setBrowserNa
50
me(browser);
51
try {
52
WebDriver driver= new
53
RemoteWebDriver(new URL("
54
HYPERLINK
55 "http://localhost/"
56 http://localhost:".concat
57 (port).concat("/wd/hub"))
58 , capability);
59 selenium = new
60 WebDriverBackedSelenium(d
61
62 river, " HYPERLINK
63 "http://www.google.com/"
64 http://www.google.com");
65 } catch
66 (MalformedURLException e)
67 {
68
69 e.printStackTrace();
70 }
71 }
72
73 @Test
74 public void search() {
75 selenium.open("/");
76 selenium.type("id=lst-
ib", "testing");
selenium.click("//input
[@value='Google
Search']");
for (int second = 0;;
second++) {
if (second >= 60)
Assert.fail("timeout"
);
try {
if (selenium
.isElementPresent("
link=Software testing -
Wikipedia, the free
encyclopedia"))
break;
} catch (Exception e) {
}
try {
Thread.sleep(1000);
} catch
(InterruptedException e)
{
// TODO Auto-
generated catch block
e.printStackTrace();
}
}
selenium.click("link=So
ftware testing -
Wikipedia, the free
encyclopedia");
for (int second = 0;;
second++) {
if (second >= 60)
Assert.fail("timeout"
);
try {
if
(selenium.isTextPresent("
Software testing"))
break;
} catch (Exception e) {
}
try {
Thread.sleep(1000);
} catch
(InterruptedException e)
{

e.printStackTrace();
}
}
}
@AfterClass
public void afterClass(){
selenium.stop();
}

}
In the above class I am using the TestNG "Parameter" property to
provide different data set to the "BeforeClass" method
"beforeClass". The beforeClass method accepts two properties
"browser" and a "port".
These values are used for initialization of driver and in-turn for
initialization of selenium object. In the above code I am using the
"WebDriverBackedSelenium" class for creation of the selenium
object, so that its easy for guys who had worked on Selenium-1
to understand the code. If you want the code to be purely
WebDriver, you can directly use the "driver" object for defining
your test-cases.
The main part in this test case is how the driver object is being
created:

DesiredCapabilities capability= new


DesiredCapabilities();
capability.setBrowserName(browser);
WebDriver driver= new RemoteWebDriver(new
URL("http://localhost:".concat(port).concat("/wd/hub"))
, capability);
The above code creates an object of DesiredCapability and then
set the browser value to it. Now using this "capability" object I
am creating the webdriver object using the "RemoteWebDriver"
class. This tells the selenium on which browser the test-case
needs to run and where the server is located. In this example I
am assuming the server to be running locally. In case it is on
different system the "localhost" needs to be re-placed with the ip
of the said system.

TestNG configuration
For parallel execution you need to use the TestNG configuration.
Following is an "testng.xml" file for the above said test class. The
said configuration executes the test-cases across different
browser.

<suite name="Selenium TestNG Suite" parallel="tests"


thread-count="5">

<test name="Selenium TestNG - 1">


<parameter name="browser" value="firefox" />
<parameter name="port" value="4444" />
<classes>
<class name="com.test.testng.Google" />
</classes>
</test>
<test name="Selenium TestNG - 2">
<parameter name="browser" value="chrome" />
<parameter name="port" value="4444" />
<classes>
<class name="com.test.testng.Google" />
</classes>
</test>

</suite>

In the above configuration, I am configuring TestNG to run "tests" in


parallel. Also there are two different tests inside a suite. For each test a
different "browser" parameter value has been configured.
Selenium-Grid server
Now start your grid using the following commands. Run each command in
a seperate terminal or command prompt by going to the directory
containing your selenium-server-standalone-2.x.x.jar. In the following
example I am using the 2.7.0 version of selenium.

For Hub:

java -jar selenium-server-standalone-2.7.0.jar -role


hub

For a firefox based node:

java -jar selenium-server-standalone-2.7.0.jar -role


webdriver -hub http://localhost:4444/grid/register
-port 5556 -browser browserName=firefox

For google-chrome based node:


java -Dwebdriver.chrome.driver=/path/to/chromedriver
-jar selenium-server-standalone-2.7.0.jar -role
webdriver -hub http://localhost:4444/grid/register
-port 5555 -browser browserName=chrome

Before running the above command you need to provide the


chrome-driver path to the property "-Dwebdriver.chrome.driver".

Now run your testng.xml from eclipse by selecting it -> Right


click -> Run as -> TestNG suite(this will work only if you have
TestNG plugin installed in your eclipse.)
Or you can choose other ways to execute "testng.xml" like from
command prompt, using ant or maven.
Once you run the above testng.xml. TestNG will execute the
cases from the Google class on grid across different browsers
firefox and google-chrome as configured.

You can do configurations for environment like


OS (Linux,Windows), browser, browser-version and all and then
you can run you cases on particular type of environment by
configuring them accordingly. More details can be found at the
following URL:
HYPERLINK "http://code.google.com/p/selenium/wiki/Grid2"
http://code.google.com/p/selenium/wiki/Grid2
Example Nine:

Data-Driven testing using Junit and TestNG

Most of the guys who are into automation may be knowing the
term Data-Driven testing. But the word will still be new for some
fresh faces in the field of automation. In this blog I will explain
what is Data-Driven testing and will give an example of Data-
driven testing using Junit and TestNG frameworks.

Data-Driven testing as the name suggests is a test driven by the


Data. For ex. You have a user detail form where you need to
enter details of multiple users and save them. Here if you have 5
different user data available and you have to write automation
cases for these, you may end up writing 5 different automation
test cases(one for each user data).
If you apply a Data-Driven approach you will end up with only
one test-case, that is filling the form with user data and then
submitting it. The test case will get executed based on the data
provided to it. In this case it will be 5 and hence the test case will
get executed 5 times with different data-set.

The advantage of using a Data-driven approach is that you


reduce your effort in writing/maintaing test-cases for your
different type of data. In case of additions or deletion of new/old
entries , you just have to change the data and not your actual
test-case.

Following I will mention a Data-Driven approach for searching on


google with different data using Junit and TestNg frameworks:

Using Junit:
HYPERLINK "http://blog.varunin.com/2011/10/data-driven-testing-
using-junit-and.html" ?
1 import static
2 org.junit.Assert.fail;
3
4 import
5 com.thoughtworks.selenium
6 .*;
7 import org.junit.After;
8 import org.junit.Before;
9 import org.junit.Test;
10
11 import
12 org.junit.runner.RunWith;
13 import
14 org.junit.runners.Paramet
15 erized;
16 import
17 org.junit.runners.Paramet
18 erized.Parameters;
19 import
20 org.openqa.selenium.WebDr
21 iver;
22 import
23 org.openqa.selenium.WebDr
24 iverBackedSelenium;
25 import
26 org.openqa.selenium.firef
27 ox.FirefoxDriver;
28
29 import java.util.Arrays;
30 import java.util.List;
31
32 @RunWith(Parameterized.cl
33 ass)
34 public class
35 JunitGoogleBase {
36 public Selenium
37 selenium;
38 WebDriver driver;
39 private String testData;
40
41 public
42 JunitGoogleBase(String
43 testData){
44 this.testData=testData
45 ;
46 }
47
48 @Parameters
49 public static List<
50 Object[]> data() {
51 return
52 Arrays.asList(new Object[]
[]{{"testing"},{"Software
53
testing"}});
54
}
55
56
57 @Before
58 public void setUp()
59 throws Exception {
60 driver= new
61 FirefoxDriver();
62 selenium = new
63 WebDriverBackedSelenium(d
64 river, " HYPERLINK
"http://www.google.com/"
http://www.google.com");
selenium.open("
HYPERLINK
"http://www.google.com/"
http://www.google.com");
}

@Test
public void testSearch()
throws Exception {
selenium.open("/");
selenium.type("id=lst-
ib", testData);
selenium.click("//inpu
t[@value='Google
Search']");
for (int second = 0;;
second++) {
if (second >= 60)
fail("timeout");
try { if
(selenium.isElementPresen
t("link=Software testing
- Wikipedia, the free
encyclopedia")) break; }
catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("link=S
oftware testing -
Wikipedia, the free
encyclopedia");
for (int second = 0;;
second++) {
if (second >= 60)
fail("timeout");
try { if
(selenium.isTextPresent("
Software testing"))
break; } catch (Exception
e) {}
Thread.sleep(1000);
}

@After
public void tearDown()
throws Exception {
selenium.stop();

}
}

Using TestNg:
HYPERLINK "http://blog.varunin.com/2011/10/data-driven-testing-
using-junit-and.html" ?
1 import
2 com.thoughtworks.selenium
3 .*;
4
5
6 import
7 org.openqa.selenium.WebDr
8 iver;
9 import
10 org.openqa.selenium.WebDr
11 iverBackedSelenium;
12 import
13 org.openqa.selenium.firef
14 ox.FirefoxDriver;
15 import org.testng.Assert;
16 import
17 org.testng.annotations.Af
18 terMethod;
19 import
20 org.testng.annotations.Be
21 foreMethod;
22 import
23 org.testng.annotations.Da
24 taProvider;
25 import
26 org.testng.annotations.Te
27 st;
28
29
30
31 public class
32 TestNGGoogleBase {
33 public Selenium
34 selenium;
35 WebDriver driver;
36
37 @DataProvider(name="par
38 ameter")
39 public static Object[]
40 [] data() {
41 return new Object[][]
42 {{"testing"},{"Software
43 testing"}};
44 }
45
@BeforeMethod
46
public void setUp()
47
throws Exception {
48
driver= new
49
FirefoxDriver();
50
selenium = new
51
WebDriverBackedSelenium(d
52
river, " HYPERLINK
53
54 "http://www.google.com/"
55 http://www.google.com");
56 selenium.open("
HYPERLINK
"http://www.google.com/"
http://www.google.com");
}

@Test(dataProvider="par
ameter")
public void
testSearch(String
testData) throws Exception
{
selenium.open("/");
selenium.type("id=lst-
ib", testData);
selenium.click("//inpu
t[@value='Google
Search']");
for (int second = 0;;
second++) {
if (second >= 60)
Assert.fail("timeout");
try { if
(selenium.isElementPresen
t("link=Software testing
- Wikipedia, the free
encyclopedia")) break; }
catch (Exception e) {}
Thread.sleep(1000);
}
selenium.click("link=S
oftware testing -
Wikipedia, the free
encyclopedia");
for (int second = 0;;
second++) {
if (second >= 60)
Assert.fail("timeout");
try { if
(selenium.isTextPresent("
Software testing"))
break; } catch (Exception
e) {}
Thread.sleep(1000);
}
}

@AfterMethod
public void tearDown()
throws Exception {
selenium.stop();
}

}<span class="Apple-
style-span" style="font-
family: Verdana, sans-
serif;">
</span>
The main difference in the above two functions is that you
provide a Paramaterized option to the class in Junit and supply
data to the constructor of the said class. Where as in TestNG you
do the same at the test-method level.

Its simple to do data-driven testing in TestNG framework as you


can provide a different data providing function for each test-
method, but the same is not possible in Junit.

Example Ten:

HYPERLINK "http://blog.varunin.com/2010/05/generating-selenium-
reports-using.html" Generating selenium reports using TestNG-xslt
through Ant
TestNG-xslt generates user friendly reports using the TestNG
results output (testng-results.xml). Its uses the pure XSL for
report generation and Saxon as an XSL2.0 implementation.
Most of the material is taken from the original site.
http://code.google.com/p/testng-xslt/

I will tell in this blog how to implement this report for your
project. This implementation will tell you how to generate the
testng-xslt report using ant. If your current project does not use
ant build then you can use ant only for the report generation
purpose.

If you dont know ant please check the Apache ant website
http://ant.apache.org/.

For generating testng-xslt report for your project do the


following:
1. Download the testng-xslt
2. Unzip and copy the testng-results.xsl from the testng-xslt
folder(testng-xslt-1.1\src\main\resources) to your own project
folder.
3. Now copy the saxon library from (testng-xslt-1.1\lib\saxon-
8.7.jar)to your project lib folder.
4. Modify your build.xml of ant and add the following target to it.

HYPERLINK "http://blog.varunin.com/search/label/Selenium
%20Reports" ?
1 <project name="test"
2 basedir=".">
3 <property name="LIB"
4 value="${basedir}/libs" />
5 <property name="BIN"
6 value="${basedir}/bin" />
7 <path id="master-
8 classpath">
9 <pathelement
10 location="${BIN}" />
11 <fileset dir="$
12 {LIB}">
13 <include
14 name="**/*.jar" />
15 </fileset>
16 </path>
17
18 <target name="testng-
19 xslt-report">
20 <delete dir="$
21 {basedir}/testng-xslt">
22 </delete>
23 <mkdir dir="$
24 {basedir}/testng-xslt">
25 </mkdir>
26 <xslt in="$
27 {basedir}/test-
28 output/testng-
29 results.xml" style="$
{basedir}/testng-
results.xsl" out="$
{basedir}/testng-
xslt/index.html">
<param
expression="$
{basedir}/testng-xslt/"
name="testNgXslt.outputDi
r" />

<param
expression="true"
name="testNgXslt.sortTest
CaseLinks" />

<param
expression="FAIL,SKIP,PAS
S,CONF,BY_CLASS"
name="testNgXslt.testDeta
ilsFilter" />

<param
expression="true"
name="testNgXslt.showRunt
imeTotals" />

<classpath
refid="master-classpath">
</classpath>
</xslt>
</target>
</project>

The XSL transformation can be configured using the parameters


described below.

testNgXslt.outputDir - Sets the target output directory for the


HTML content. This is mandatory and must be an absolute path.
If you are using the Maven plugin this is set automatically so you
don't have to provide it.
testNgXslt.cssFile - Specifies and alternative style sheet file
overriding the default settings. This parameter is not required.
testNgXslt.showRuntimeTotals - Boolean flag indicating if the
report should display the aggregated information about the
methods durations. The information is displayed for each test
case and aggregated for the whole suite. Non-mandatory
parameter, defaults to false.
testNgXslt.reportTitle - Use this setting to specify a title for
your HTML reports. This is not a mandatory parameter and
defaults to "TestNG Results".
testNgXslt.sortTestCaseLinks - Indicates whether the test
case links (buttons) in the left frame should be sorted
alphabetically. By default they are rendered in the order they are
generated by TestNG so you should set this to true to change this
behavior.
testNgXslt.chartScaleFactor - A scale factor for the SVG pie
chart in case you want it larger or smaller. Defaults to 1.
testNgXslt.testDetailsFilter - Specified the default settings for
the checkbox filters at the top of the test details page. Can be
any combination (comma-separated) of:
FAIL,PASS,SKIP,CONF,BY_CLASS
You need to provide the testng-xslt stylesheet the TestNG results
xml(testng-results.xml) , the path to the style sheet testng-
results.xsl and the output index.html path.

Also dont forget to add the saxon library to your target classpath
else you will get an error. In my case it is the master-classpath.

Noe run the ant target for report generation (in my case "testng-
xslt-report") and check the ouput folder configured by you for
testng-xslt report.

Example Eleven:

How to take a screenshot at the end of your Selenium WebDriver


tests?
INCLUDEPICTURE "http://www.muhuk.com/wp-
content/uploads/2012/02/webdriver_screenshot-300x270.png" \*
MERGEFORMATINET
When you run HYPERLINK "http://seleniumhq.org/"
Selenium headless on the server, debugging failures with just the
standard outputs can be challenging. A screenshot of the last
state of the browser helps in this case. This little tutorial explains
how to take such a screenshot and save it as an artifact in
Jenkins. I will be using HYPERLINK "http://www.junit.org/"
junit as the test framework.

Step 0: Getting the name of the current test


You probably want to include the name of the test class and the
name of the current test method in the filename. Here is how you
find it out:
import org.junit.After;
import org.junit.Rule;
import org.junit.rules.TestName;
public abstract class Test {
@Rule public TestName testName = new
TestName();

@After public void tearDown() {


String className =
this.getClass().getSimpleName();
String methodName =
this.testName.getMethodName();
System.err.println("Finished test " +
className + "." +
methodName + "()");
}
}
The code above is just a simple demonstration of how you
use TestName. However it is a good idea to produce a simple
output like above in the beginning and the end of each test.

Step 1: Taking the screenshot


HYPERLINK
"http://seleniumhq.org/docs/04_webdriver_advanced.html" \l
"taking-a-screenshot" Selenium documentation suggests the
following:
import org.junit.After;
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

public abstract class Test {


@After public void tearDown() {
// driver is your WebDriver
File screenshot = ((TakesScreenshot)
driver)

.getScreenshotAs(OutputType.FILE);
}
}
Example code in the official documentation is a little more terse, I
left out everything but the essentials.

Step 2: Saving the image


getScreenshotAs() method saves the output in a temporary
location. I took HYPERLINK
"http://stackoverflow.com/a/3423347/42188" the advice
here and used FileUtils.copyFile() to copy this temporary file
back inside my workspace.
import org.junit.After;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public abstract class Test {


@After public void tearDown() {
// screenshot is the file we have acquired
// fileName is the name of the image file
try {
FileUtils.copyFile(screenshot, new
File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
}
To give a concrete example, if your fileName is "screenshot-
TestClass-testName.png", it will be copied
to $WORKSPACE/screenshot-TestClass-testName.png.

Step 3: Archiving the screenshot as an artifact


In Post-build Actions section enable Archive the artifacts and
enter the appropriate glob in the textbox below. Your screenshots
will appear in the Build Artifacts in build details page

You might also like