Selenium Real Time Scenarios PDF
Selenium Real Time Scenarios PDF
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;
@BeforeClass(alwaysRun = true)
protected void startWebDriver() {
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 120);
}
@AfterClass(alwaysRun = true)
protected void closeSession() {
driver.close();
}
VisibilityOfElementLocated.java
package tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
By findCondition;
VisibilityOfElementLocated(By by) {
this.findCondition = by;
}
WebmailTest.java
package tests;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
//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();
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')]")));
}
//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();
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;
@Test
public void f() throws InterruptedException {
//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();
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");
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.
Iterator<String> windowIterator =
browser.getWindowHandles();
while(windowIterator.hasNext()) {
if (popup.getTitle().equals("Google") {
break;
popup.findElement(By.name("q")).sendKeys("Thoughtworks");
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
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
}
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:
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;
driver.findElement(By.id("gbqfq")).sendKeys(s);
driver.findElement(By.name("btnK")).click();
System.setProperty("webdriver.chrome.driver",
"D:/sreekumar/Tutorial/Selenium/chromedriver_win_18.0.995.0/
chromedriver.exe");
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;
__________________________________________________________________
________________
Example Eight:
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:
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>
For Hub:
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.
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.
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/.
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>
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:
.getScreenshotAs(OutputType.FILE);
}
}
Example code in the official documentation is a little more terse, I
left out everything but the essentials.