51
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(); }

Selenium Real Time Scenarios.doc

Embed Size (px)

DESCRIPTION

Selenium

Citation preview

Page 1: Selenium Real Time Scenarios.doc

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); } }

Page 2: Selenium Real Time Scenarios.doc

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 { 

//variablespublic 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() {

Page 3: Selenium Real Time Scenarios.doc

//new message variablesString to = HOTMAIL_EMAIL;String subject = "Test Sending Email Message From Yahoo";String message = "This is a test e-mail from Yahoo";

 //login to yahoodriver.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 messagedriver.findElement(By.id("compose_button_label")).click();wait.until(new

VisibilityOfElementLocated(By.xpath("id('_testTo_label')/ancestor::tr[1]//textarea"))); 

//send test messagedriver.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 herewait.until(new

VisibilityOfElementLocated(By.xpath("//nobr[contains(text(), 'Message Sent')]")));

@Test(description = "Sends an e-mail from Hotmail account")public void sendFromHotmail() {

//new message variablesString to = YAHOO_EMAIL;String subject = "Test Sending Email Message From Hotmail";

Page 4: Selenium Real Time Scenarios.doc

String message = "This is a test e-mail from Hotmail"; 

//login to hotmaildriver.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 messagedriver.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")).getText(), "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;

Page 5: Selenium Real Time Scenarios.doc

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

Page 6: Selenium Real Time Scenarios.doc

              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_Windows);                           // Open second  popup              jasminedriver.findElement(By.xpath("//*[@id='content']/div[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);

Page 7: Selenium Real Time Scenarios.doc

              System.out.println();              Thread.sleep(3000L);                           System.out.println("Centered_Popup");  }  @BeforeMethod  public void beforeMethod() {               jasminedriver.get("http://www.quackit.com/javascript/popup_windows.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

Page 8: Selenium Real Time Scenarios.doc

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;

Page 9: Selenium Real Time Scenarios.doc

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();"

Page 10: Selenium Real Time Scenarios.doc

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 SuiteThe 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:

123456789

10

package com.ncona;

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;

Page 11: Selenium Real Time Scenarios.doc

1112131415161718192021222324252627282930313233343536373839404142434445464748

public class NconaTestSuite{  public static void main( HYPERLINK "http://www.google.com/search?hl=en&q=allinurl%3Astring+java.sun.com&btnI=I%27m%20Feeling%20Lucky" String[] args)    {        // Objects that are going to be passed to all test classes        WebDriver driver = new FirefoxDriver();        Wait<WebDriver>wait = new WebDriverWait(driver, 30);

        boolean result;        try        {            // Here we add all the test classes we want to run            MiscTestClass mtc1 = new MiscTestClass();            MiscTestClassTwo mtc2 = new MiscTestClassTwo();            MiscTestClassThree mtc3 = new MiscTestClassThree();

            // We call the run method (that method runs all            // the tests of the class) for each of the classes

Page 12: Selenium Real Time Scenarios.doc

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/search?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/search?hl=en&q=allinurl%3Asystem+java.sun.com&btnI=I%27m%20Feeling%20Lucky" System.out.println("Test " + (result ? "passed." : "failed."));        if (!result)        {             HYPERLINK

Page 13: Selenium Real Time Scenarios.doc

"http://www.google.com/search?hl=en&q=allinurl%3Asystem+java.sun.com&btnI=I%27m%20Feeling%20Lucky" System.exit(1);        }    }}

Test ClassOur 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:

123456789

1011121314151617181920212223242526

package com.ncona;

import java.util.List;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.Wait;import org.openqa.selenium.support.ui.WebDriverWait;

public class MiscTestClass{    static WebDriver driver;  static Wait<WebDriver> wait;

  public static boolean run(Web

Page 14: Selenium Real Time Scenarios.doc

272829303132333435363738394041424344

Driver driverArg, Wait<WebDriver> waitArg)    {        driver = driverArg;        wait = waitArg;

        setUp();

        // Run all the methods and return false if any fails        return (            miscMethod()            && miscMethod2()        );    }

  private static boolean miscMethod()    {        // Put your tests code here

        return result    }

  private static boolean miscMethod2()    {        // Put your tests code here

        return result    }}

Build file

Page 15: Selenium Real Time Scenarios.doc

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:

123456789

1011121314151617181920212223242526272829303132

<project basedir="." name="Test Automation">  <property name="src.dir" value="${basedir}/java/src"/>  <property name="classes.dir" value="${basedir}/java/classes/main"/>  <property name="lib.dir" value="${basedir}/lib"/>  <property name="build.dir" value="${basedir}/build"/>  <property name="testautomation.jar" value="${build.dir}/testautomation.jar"/>

  <path id="testautomation.classpath">        <file file="${testautomation.jar}"/>        <fileset dir="${lib.dir}">          <include name="*.jar" />        </fileset>    </path>

  <target name="build" description="sets up the environment for test

Page 16: Selenium Real Time Scenarios.doc

execution">        <mkdir dir="${classes.dir}"/>        <mkdir dir="${build.dir}"/>        <javac debug="true"              srcdir="${src.dir}"              destdir="${classes.dir}"            includeAntRuntime="false"            classpathref="testautomation.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.ncona.${example}"               failonerror="true"              classpathref="testautomation.classpath"/>    </target></project>

Run the suiteFirst we need to build the project:

1ant build

Page 17: Selenium Real Time Scenarios.doc

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 examplesExample 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;

Page 18: Selenium Real Time Scenarios.doc

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();

Page 19: Selenium Real Time Scenarios.doc

}}

Example Seven:

Uploading Files in Remote WebDriverMarch 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;

Page 20: Selenium Real Time Scenarios.doc

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();    }}

__________________________________________________________________________________

Page 21: Selenium Real Time Scenarios.doc

Example Eight:

Selenium Grid with WebDriverI 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-22. Java 1.6 and above3. TestNg jar . You can download it from the link:  HYPERLINK "http://testng.org/doc/download.html" TestNG4. Eclipse with TestNG plugin installed(optional)5. ChromeDriver. Can be downloaded from:  HYPERLINK "http://code.google.com/p/chromium/downloads/list" ChromeDriver

The Test CodeFollowing 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" ?12345678910

import java.net.MalformedURLException;import java.net.URL; import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebDr

Page 22: Selenium Real Time Scenarios.doc

11121314151617181920212223242526272829303132333435363738394041424344454647484950

iverBackedSelenium;import org.openqa.selenium.remote.DesiredCapabilities;import org.openqa.selenium.remote.RemoteWebDriver;import org.testng.annotations.AfterClass;import org.testng.annotations.BeforeClass;import org.testng.annotations.Parameters;import org.testng.annotations.Test; import com.thoughtworks.selenium.Selenium; import junit.framework.Assert; public class Google { private Selenium selenium; @Parameters({"browser","port"}) @BeforeClass public void beforeClass(String browser,String port){  DesiredCapabilities capability= new DesiredCapabilities();  capability.setBrowserNa

Page 23: Selenium Real Time Scenarios.doc

5152535455565758596061626364656667686970717273747576

me(browser);  try {   WebDriver driver= new RemoteWebDriver(new URL(" HYPERLINK "http://localhost/" http://localhost:".concat(port).concat("/wd/hub")), capability);   selenium = new WebDriverBackedSelenium(driver, " HYPERLINK "http://www.google.com/" http://www.google.com");  } catch (MalformedURLException e) {       e.printStackTrace();  } }   @Test public void search() {  selenium.open("/");  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

Page 24: Selenium Real Time Scenarios.doc

encyclopedia"))     break;   } catch (Exception e) {   }   try {    Thread.sleep(1000);   } catch (InterruptedException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  }  selenium.click("link=Software 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();   }  } }

Page 25: Selenium Real Time Scenarios.doc

 @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 configurationFor 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.

Page 26: Selenium Real Time Scenarios.doc

<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 serverNow 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

Page 27: Selenium Real Time Scenarios.doc

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/Grid2Example Nine:

Page 28: Selenium Real Time Scenarios.doc

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" ?1234567

import static org.junit.Assert.fail; import com.thoughtworks.selenium.*;import org.junit.After;

Page 29: Selenium Real Time Scenarios.doc

891011121314151617181920212223242526272829303132333435363738394041424344454647

import org.junit.Before;import org.junit.Test; import org.junit.runner.RunWith;import org.junit.runners.Parameterized;import org.junit.runners.Parameterized.Parameters;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebDriverBackedSelenium;import org.openqa.selenium.firefox.FirefoxDriver; import java.util.Arrays;import java.util.List; @RunWith(Parameterized.class)public class JunitGoogleBase {  public Selenium selenium;  WebDriver driver;  private String testData;     public JunitGoogleBase(String testData){   this.testData=testData;  }   

Page 30: Selenium Real Time Scenarios.doc

4849505152535455565758596061626364

  @Parameters   public static List< Object[]> data() {    return Arrays.asList(new Object[][]{{"testing"},{"Software testing"}});   }   @Before  public void setUp() throws Exception {   driver= new FirefoxDriver();   selenium = new WebDriverBackedSelenium(driver, " 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("//input[@value='Google Search']");   for (int second = 0;; second++) {    if (second >= 60) fail("timeout");    try { if (selenium.isElementPresen

Page 31: Selenium Real Time Scenarios.doc

t("link=Software testing - Wikipedia, the free encyclopedia")) break; } catch (Exception e) {}    Thread.sleep(1000);   }   selenium.click("link=Software 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" ?1234

import com.thoughtworks.selenium.*; 

Page 32: Selenium Real Time Scenarios.doc

567891011121314151617181920212223242526272829303132333435363738394041424344

 import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebDriverBackedSelenium;import org.openqa.selenium.firefox.FirefoxDriver;import org.testng.Assert;import org.testng.annotations.AfterMethod;import org.testng.annotations.BeforeMethod;import org.testng.annotations.DataProvider;import org.testng.annotations.Test;   public class TestNGGoogleBase {  public Selenium selenium;  WebDriver driver;     @DataProvider(name="parameter")   public static Object[][] data() {    return new Object[][]{{"testing"},{"Software testing"}};   }

Page 33: Selenium Real Time Scenarios.doc

454647484950515253545556

   @BeforeMethod  public void setUp() throws Exception {   driver= new FirefoxDriver();   selenium = new WebDriverBackedSelenium(driver, " HYPERLINK "http://www.google.com/" http://www.google.com");    selenium.open(" HYPERLINK "http://www.google.com/" http://www.google.com");  }   @Test(dataProvider="parameter")  public void testSearch(String testData) throws Exception {   selenium.open("/");   selenium.type("id=lst-ib", testData);   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) {}    Thread.sleep(1000);

Page 34: Selenium Real Time Scenarios.doc

   }   selenium.click("link=Software 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.

Page 35: Selenium Real Time Scenarios.doc

Example Ten:

HYPERLINK "http://blog.varunin.com/2010/05/generating-selenium-reports-using.html" Generating selenium reports using TestNG-xslt through AntTestNG-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-xslt2. 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" ?1234567

<project name="test" basedir=".">    <property name="LIB" value="${basedir}/libs" />    <property name="BIN" value="${basedir}/bin" />    <path id="master-

Page 36: Selenium Real Time Scenarios.doc

891011121314151617181920212223242526272829

classpath">        <pathelement location="${BIN}" />        <fileset dir="${LIB}">            <include name="**/*.jar" />        </fileset>    </path>         <target name="testng-xslt-report">        <delete dir="${basedir}/testng-xslt">        </delete>        <mkdir dir="${basedir}/testng-xslt">        </mkdir>        <xslt in="${basedir}/test-output/testng-results.xml" style="${basedir}/testng-results.xsl" out="${basedir}/testng-xslt/index.html">            <param expression="${basedir}/testng-xslt/" name="testNgXslt.outputDir" />             <param expression="true" name="testNgXslt.sortTestCaseLinks" />             <param expression="FAIL,SKIP,PASS,CONF,BY_CLASS"

Page 37: Selenium Real Time Scenarios.doc

name="testNgXslt.testDetailsFilter" />             <param expression="true" name="testNgXslt.showRuntimeTotals" />             <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.

Page 38: Selenium Real Time Scenarios.doc

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_CLASSYou 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

Page 39: Selenium Real Time Scenarios.doc

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 {

Page 40: Selenium Real Time Scenarios.doc

@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.

Page 41: Selenium Real Time Scenarios.doc

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