Вы находитесь на странице: 1из 232

Technical Challenges with Selenium

WHAT ARE THE TECHNICAL CHALLENGES WITH SELENIUM?


As you know Selenium is a free ware open source testing tool. There are many challenges with Selenium.

1. Selenium supports only web based applications.

2. It doesn't support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications.

3. When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability
of the test cases.

4. Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications.

5. There is no object repository concept in Selenium, so maintainability of the objects is very high

6. There are many challenges if one have to interact with Win 32 windows even when you are working with Web based applicati
ons.

7. Bitmap comparison is not supported by Selenium.

8. Any reporting related capabilities, you need to depend on third party tools.

9. You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently with the scriptin
g side of selenium.
JUnit 4 Vs TestNG
BELOW ARE SOME OF THE DIFFERENCES LISTED BETWEEN JUNIT 4 AND TESTNG
1. ANNOTATION @TEST IS USED IN BOTH JUNIT4 AND TESTNG BUT FROM DIFFERENT CLASS:

import org.junit.Test; // JUnit 4


or

import org.testng.annotations.Test; // TestNG

public class MyTestClass {


@Test public void aTestMethod() throws ...
{ ...
}

2. ACCORDING TO ANNOTATION SUPPORT:

Feature JUnit 4 TestNG


Test annotation @Test @Test
Run before all tests in this suite have run @BeforeSuite
Run after all tests in this suite have run @AfterSuite
Run before the test @BeforeTest
Run after the test @AfterTest
Run before the first test method that belongs
@BeforeGroups
to any of these groups is invoked
Run after the last test method that belongs to
@AfterGroups
any of these groups is invoked
Run before the first test method in the current
@BeforeClass @BeforeClass
class is invoked
Run after all the test methods in the current
@AfterClass @AfterClass
class have been run
Run before each test method @Before @BeforeMethod
Run after each test method @After @AfterMethod
Ignore test @ignore @Test(enbale=false)
@Test(expected = @Test(expectedExceptions =
Expected exception
ArithmeticException.class) ArithmeticException.class)
Timeout @Test(timeout = 1000) @Test(timeout = 1000)

3. EXCEPTION TEST

It explains what exception will throw from the unit test.


//JUnit4
@Test(expected = ArithmeticException.class)

public void divisionByZeroException() {


int i = 1/0;
}

//TestNG
@Test(expectedExceptions = ArithmeticException.class)

public void divisionByZeroException() {


int i = 1/0;
}

4. Ignore Test

It explains how to ignore the unit test.

//JUnit

@Ignore("Not Ready to Run")


@Test
public void IgnoreTest() {
System.out.println("Method is not ready yet");
}

//TestNG

@Test(enabled=false)
public void IgnoreTest() {
System.out.println("Method is not ready yet");
}
5. SUITE TEST
5. Suite Test

It explains how to bundle a few unit test and run together.


//JUnit4
The "@RunWith" and "@Suite" are use to run the suite test. The below class means both unit test "JunitTest1" and "JunitTest2"
run together after "JunitTest3" executed. All the declaration is define inside the class.

@RunWith(Suite.class)
@Suite.SuiteClasses({
JunitTest1.class,
JunitTest2.class
})
public class JunitTest3 {
}

//TestNG
XML file is use to run the suite test. The below XML file means both unit test TestNGTest1 and TestNGTest2 will run it
together.

<suite name="My test suite">


<test name="My test">
<classes>
<class name="example.test.TestNGTest1" />
<class name="example.test.TestNGTest2" />
</classes>
</test>
</suite>

6. DEPENDENCY TEST
It explains which test will execute after what test. If the dependent method fails, then all subsequent tests will be skipped, not
marked as failed.

//JUnit4
JUnit framework is focus on test isolation; it did not support this feature at the moment.

//TestNG

It use "dependOnMethods" to implement the dependency testing as following

@Test
public void testMethod1() {
System.out.println("This is method 1");
}

@Test(dependsOnMethods={"testMethod1"})
public void testMethod2() {
System.out.println("This is method 2");
}

7. PARAMETERIZED TEST

It says how to pass parameters to an unit test dynamically.

//JUnit4
The "@RunWith" and "@Parameter" is use to provide parameter value for unit test, @Parameters have to return List[], and the
parameter will pass into class constructor as argument.

@RunWith(value = Parameterized.class)
public class JunitTest {
private int number;
public JunitTest(int number) {
this.number = number;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
return Arrays.asList(data);
}
@Test
public void pushTest() {
System.out.println("Parameterized Number is : " + number);
}
}
It has many limitations here; we have to follow the JUnit way to declare the parameter, and the parameter has to pass into
constructor in order to initialize the class member as parameter value for testing. The return type of parameter class is List *+,
data has been limited to String or a primitive value for testing.

//TestNG
XML file or @DataProvider is used to provide vary parameter for testing.

ADVANTAGES OF WEB DRIVER


1) Support for iPhone and Android testing
2) Implementation of listeners - a much awaited feature
3) Better features for Ajax testing.
4) You can easily simulate clicking on front and back button of browser.
5) You can extract objects in bulk like QTP. For ex - extract all links of page. With RC this was a big hastle
6) Unlike RC you dont have to start a server in webdriver.
7) You can simulate movement of a mouse using selenium.
8) Tabs and pops are more or less the same. RC can also handle and Webdriver can also handle.
9) You can find coordinates of any object using Webdriver.
10) You have classes in Webdriver which help you to simulate key press events of keyboard.
10) Keyword driven framework is very easy to build in webdriver.
TestNG Basic Concepts and Annotations

2) TESTNG BASIC CONCEPTS AND ANNOTATIONS


3)
4) TestNG engine supports a series of annotations, with these annotations it even has stronger flexibility and extensibility
than Junit, we will seethese annotations one by one in detail, first of all, let us have a quick look at the life cycle of a
typical TestNG case.
5)

6)
7)
8) From the given illustration, we know that the life-cycle of a TestNG case starts with @BeforeClass and ends
with@AfterClass. @BeforeClass/@AfterClass methods will be run before/after any method in a given is run, they are
designed for those expensive resource initialization/cleanup and recovery, we didnt put @BeforeSuite,
@BeforeGroups, @AfterGroups and @AfterSuite to this illustration, but if they were, they will be ran even
before @BeforeClass or after @AfterClass. @Configuration is deprecated so we dont recommend use it.
9)
10) TESTNG BASIC ANNOTATIONS FOR CONFIGURATION METHODS

Pri Annotation name Documentation

1 @BeforeSuite Annotates methods that will be run before any method in a given is run.

2 Annotates methods that will be run before the first method in any of the specified groups is
@BeforeGroups
run.

3 @BeforeClass Annotates methods that will be run before the first method on the current test class is run.
4 @BeforeTest Annotates methods that will be run before any method in a given is run.

5 @BeforeMethod Annotates methods that will be run before each test method.

6 @AfterMethod Annotates methods that will be run after every test method.

7 @AfterTest Annotates methods that will be run after all the test methods in a given have been run.

8 @AfterClass Annotates methods that will be run after the last test method on the current class is run.

9 Annotates methods that will be run after the last test method belonging to the groups
@AfterGroups specified in its value attribute has been run. The annotated method is automatically put into
these specified groups.

10 @AfterSuite Annotates methods that will be run after all the test methods in a given have been run.

11) The annotations @Test annotates a method as test case in TestNG pattern.
12)
13)
Simple Example with TestNG Annotations

package com.My_Project;
import org.testng.annotations.*;
public class TestNGTest {
@BeforeGroups
public void BeforeGroups() {
System.out.println("@BeforeGroups");
}
@BeforeClass
public void BeforeClass() {
System.out.println("@BeforeClass");
}
@Test(groups = {"My group"})
public void test1() {
System.out.println("test1");
}
@Test
public void test2() {
System.out.println("test2");
}
@AfterClass
public void AfterClass() {
System.out.println("@AfterClass");
}
AfterMethod
public void AfterMethod() {
System.out.println("@AfterMethod");
}
}
Here is the output of this Above code
[Parser] Running:
C:\Users\Administrator\.IntelliJIdea70\system\temp-testng-customsuite.xml
@BeforeClass
test1
@AfterMethod
test2
@AfterMethod
@AfterClass
===============================================
Custom suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
Selenium Basics
WHAT IS SELENIUM ?

Selenium is a Testing framework for web applications, having 3 variants:

Selenium IDE

- Firefox add-on

- Record and playback user actions on a web site


- Not recommend for stable, long staying test suites

Selenium RC (Remote Control, Selenium 1)

- Java Server that controls various browsers


- Executes scripted user actions from a typically JUnit programming environment,
- Has a string-based programming API
- Supports variety of browsers (Internet Explorer , Firefox, safari, chrome, opera etc )

Selenium WebDriver (Selenium 2)

- Java Library, which controls the browser


- Has a object-oriented programming API
- Supports Internet Explorer, Firefox, Chrome and HtmlUnit as drivers

I recommend using the WebDriver API!


WebDriver with TestNG - Gmail Login Functionality
Below is the code for GMAIL Login functionality using WebDriver with TestNG

package com.test.webdriver;
import static org.testng.AssertJUnit.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Driver {


private WebDriver driver;
@BeforeClass
public void Startup(){
driver = new FirefoxDriver();
}
@Test (description="Google Login")
public void GoogleLogin() throws Exception{
driver.get("http://www.gmail.com");
assertEquals("Sign in", driver.findElement(By.id("signIn")).getAttribute("value"));
driver.findElement(By.id("Email")).sendKeys("*********");
driver.findElement(By.id("Passwd")).sendKeys("**********");
driver.findElement(By.id("signIn")).click();
Thread.sleep(10000);
driver.switchTo().frame("canvas_frame");
driver.findElement(By.id("gbgs4dn")).click();
driver.findElement(By.id("gb_71")).click();
driver.switchTo().defaultContent();
assertEquals("Sign in to Gmail", driver.findElement(By.id("button")).getText());
}
@AfterClass
public void teardown(){
driver.quit();
}
}
Selenium Web Driver Command List
Command Description

driver.get("http://www.google.com"); To open an application


driver.findElement(By.id("passwd-id")); Finding Element using Id
driver.findElement(By.name("passwd")); Finding Element using Name
driver.findElement(By.xpath("//input*@id=passwd-id+")); Finding Element using Xpath
element.sendKeys("some text"); To type some data
element.clear(); clear thecontents of a text eld or textarea
driver.findElement(By.xpath("//select")); Selecting the value
select.findElements(By.tagName("option")); Selecting the value
select.deselectAll(); This will deselect all OPTIONs from the rst SELECT on the page
select.selectByVisibleText("Edam"); select the OPTION withthe displayed text of Edam
findElement(By.id("submit")).click(); To click on Any button/Link
driver.switchTo().window("windowName"); Moving from one window to another window
driver.switchTo().frame("frameName"); swing from frame to frame (or into iframes)
driver.switchTo().frame("frameName.0.child"); to access subframes by separating the path with a dot, and you can specify the
frame by itsindex too.
driver.switchTo().alert(); Handling Alerts
driver.navigate().to("http://www.example.com"); To Navigate Paeticular URL
driver.navigate().forward(); To Navigate Forward
driver.navigate().back(); To Navigate Backword
driver.close() Closes the current window
driver.quit() Quits the driver and closes every associated window.
driver.switch_to_alert() Switches focus to an alert on the page.
driver.refresh() Refreshes the current page.
driver.implicitly_wait(30) Amount of time to wait
driver.set_script_timeout(30) The amount of time to wait
driver.get_screenshot_as_file('/Screenshots/foo.png') The full path you wish to save your screenshot to
driver.get_screenshot_as_base64() Gets the screenshot of the current window as a base64 encoded string which is useful in
embedded images in HTML

using functions in xpath in selenium


How to use functions in xpath in selenium

Automation using selenium is a great experience. It provides many way to identify an object or element on the web page.
But sometime we face the problems of identifying the objects on a page which have same attributes. When we get more than
one element which are same in attribute and name like multiple check boxes with same name and same id. More than one
button having
same name and ids. There are no way to distinguishes those element. In this case we have problem to instruct selenium to
identify a particular object on a web page.

I am giving you a simple example . In the below html source there are 6 check boxes are there having same type and same
name.

It is really tough to select third or fifth.

input type='checkbox' name='chk' first


input type='checkbox' name='chk' second
input type='checkbox' name='chk' third
input type='checkbox' name='chk' forth
input type='checkbox' name='chk' fifth
input type='checkbox' name='chk' sixth
There are some functions we can use in Xpath to identify the object in above cases. An XPath expression can return one of four
basic XPath data types:

* String
* Number
* Boolean
* Node-set

XPath Type : Functions


Node set : last(), position(), count(), id(), local-name(), namespace-uri(), name()
String : string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-
space(), translate()
Boolean : boolean(), not(), true(), false(), lang()
Number : number(), sum(), floor(), ceiling(), round()

I will show you how we can use some of these above functions in xpath to identify the objects.
Node Set : last()
In the above html file there are six check boxes and all are having same attributes (same type and name)

1. How we can select the last checkbox based on the position. We can use last() function to identify the last object among all
similar objects.
Below code will check or uncheck the last checkbox.
selenium.click("xpath=(//input[@type='checkbox'])[last()]");

2. How we can select the second last check box and third last check box. We can use last()- function to identify the last object
among all similar objects.
Below code will check or uncheck the second last checkbox and thrid last checkbox respectively.
selenium.click("xpath=(//input[@type='submit'])[last()-1]");
selenium.click("xpath=(//input[@type='submit'])[last()-2]");

Node Set : position()


If you want to select any object based on their position using xpath then you can use position() function in xpath.
You want to select second checkbox and forth checkbox then use below command
selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");
selenium.click("xpath=(//input[@type='checkbox'])[position()=4]");
above code will select second and forth checkbox respectively.

String : starts-with()
Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically.
Each time id gets generated differently. So to handle this situation we use some JavaScript functions.
XPath: //button[starts-with(@id, 'continue-')]

Sometimes an element gets identified by a value that could be surrounded by other text, then contains function can be used.

To demonstrate, the element can be located based on the suggest class without having
to couple it with the top and business classes using the following
XPath: //input[contains(@class, 'suggest')].

TestNG Dependency Test


TestNG Dependency Test

The Dependency Test means methods are test base on dependency. If the dependent method fails, all the subsequent test
methods will be skipped, not marked as failed.

TestNG uses dependOnMethods to implement the dependency testing as following

import org.testng.annotations.*;

/**

* TestNG Dependency Test

*/

public class TestNGTest7 {

@Test

public void method1() {

System.out.println("This is method 1");

@Test(dependsOnMethods={"method1"})

public void method2() {

System.out.println("This is method 2");

}
Result

PASSED: method1

PASSED: method2

The method2() will execute only if method1() is run successfully, else method2() will skip.

TestNG Ignore Test

This Ignored means the method is not ready to test, the TestNG engine will just bypass this method.

import org.testng.annotations.*;

/**
* TestNG Ignore Test
*
*
*/
public class TestNGTest3 {

@Test(enabled=false)
public void divisionWithException() {
System.out.println("Method is not ready yet");
}

In above example, TestNG will not test the divisionWithException() method.

estNG Suite Test

TESTNG SUITE TEST

The Suite Test means bundle a few unit test cases and run it together.

In TestNG, XML file is use to define the suite test. The below XML file means both unit test TestNGTest1 and TestNGTest2
will execute together.

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >


<suite name="My test suite">
<test name="testing">
<classes>
<class name="TestNGTest1" />
<class name="TestNGTest2" />
</classes>
</test>
</suite>

Beside classes bundle testing, TestNG provides a Grouping feature to bundle few methods as a single unit for testing, where
every method is tie to a group.

For example, Heres a class with four methods, three groups (method1, method2 and method3)

import org.testng.annotations.*;
/*
*
* TestNG Grouping *
*
*/

public class TestNGTest5_2_0 {


@Test(groups="method1")
public void testingMethod1() {
System.out.println("Method - testingMethod1()");
}

@Test(groups="method2")
public void testingMethod2() {
System.out.println("Method - testingMethod2()");
}

@Test(groups="method1")
public void testingMethod1_1() {
System.out.println("Method - testingMethod1_1()");
}

@Test(groups="method4")
public void testingMethod4() {
System.out.println("Method - testingMethod4()");
}

You can execute the unit test with group method1 only.

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >


<suite name="My test suite">
<test name="testing">
<groups>
<run>
<include name="method1"/>
</run>
</groups>
<classes>
<class name="TestNGTest5_2_0" />
</classes>
</test>
</suite>
Result:
Method - testingMethod1_1()
Method - testingMethod1()

TestNG Grouping is highly flexible and useful, especially when you implement it in your project integration testing.

Interview Questions

FEW INTERVIEW QUESTIONS FOR SELENIUM WEBDRIVER WITH JAVA

-What class should be extended to use Serialization?


-What is list and set?
-what is hash table?
-what is iterator?
-Tell me about binary search?
-Tell me about buble sort?
-What is Selenium IDE
-How can we do Iphone and Android app testing in selenium
-What technical issues did you face in selenium
-What is Selenium RC and WebDriver. What is the difference in them (2)
-How many ways can can start the selenium server (1)
-How will you convert integer to String and String to integer in Java (1)
-What do you mean by Object oriented programming. How is it used in selenium? (1)
-how do you download and install selenium? (1)
-Where do you write selenium code if you implement in java (1)
-What all languages are supported by selenium (1)
-What is Murex testing? Do we use Selenium to test Murex? (3)
-How to Integrate Jenkins Hudson integration with selenium for running the scripts in schdule time? (6)
-How to compare Text (not Html strings ) (2)
-How to open csv file (1)
-How to run webdriver scripts with different browsers
-How to do web service testing using selenium webdriver.
-How to identify webElement on web Page
-How to draw an annotation(s) on map using selenium webdriver?
-how to handle list(selecting more than one item) in Rc and Webdriver
-how to handle filedownload in ie and chrome
-How to handle silver light objects
-How to handles Popups!

-Interview Ques: How to extract data from webtable or weblist, store it in a file and sort the file

-Is there Assert.assertNotEquals() in webdriver ?

-Can we schedule the execution of test cases


-Do you any automation tool for desktop application testing?
-How to verify if the webElement is present or not on the webpage..??
-what are reflection api and how are they used in selenium ?
-How to schedule selenium suite using RC and WebDriver
-How to create a new file using Java
-How do you run your automated tests on Mutliple browsers
-How to handle certification error
-How would you deal with Ajax issues?
-What is most difficult challenge you have faced in automating a web application
-How to execute selenium webdriver tests after completion and deployment of build thru Jenkins?
-Give two examples of functionality that cannot be properly tested with automated testing software?
--List the advantage/disadvantages: Selenium WebDriver Vs QTP
-What is inheritance in Java? How is it applied in Selenium?
-What are the drawbacks of Webdriver?
-Give me 5 points about what is the use of Framework (jUnit or TestNg)
-What is the difference between verify and Assert?
-How to run the test script in selenium on specific time?
-What to do at very first if you want to start a Selenium automation tool in your project?
-How do we keep expected result in the Seleniumj automation script?
-What is the use of Class HtmlUnitDriver and when we have to use the Class HtmlUnitDriver
-can we handle windows popup using selenium?
-There are 3 fields like House Number, Mobile Number and email address. How will you validate fields

-What is the difference between client-server application and web application?


-How can you test application in multiple browsers in selenium when making the framework
-How will you run 1000 test cases and generate reports
-What are user extensions
-What is difference between QTP and selenium
-What is the architecture of selenium WebDriver
Write results to excel sheet
Write results to excel sheet

After successfully executing scripts, every one want to write results to excel sheet..here is the way to write results to excel
sheet....
Below is the sample script to write results to excel sheet...
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;

public class Importexport1 {


public Selenium selenium;
public SeleniumServer seleniumserver;
@BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://");
seleniumserver.start();
selenium.start();
}
@Test
public void testImportexport1() throws Exception {
// Read data from excel sheet
FileInputStream fi = new FileInputStream(
"F:\\Framework\\testdata\\Login1_Credentials.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
String a[][] = new String[s.getRows()][s.getColumns()];
// Write the input data into another excel file
FileOutputStream fo = new FileOutputStream(
"F:\\Framework\\Results\\LoginResult1.xls");
WritableWorkbook wwb = Workbook.createWorkbook(fo);
WritableSheet ws = wwb.createSheet("loginresult1", 0);
selenium.open("http://www.gmail.com");
selenium.windowMaximize();
System.out.println("s.getRows() = " + s.getRows());
for (int i = 0; i < s.getRows(); i++) {
System.out.println("s.getColumns = " + s.getColumns());
for (int j = 0; j < s.getColumns(); j++) {
a[i][j] = s.getCell(j, i).getContents();
Label l = new Label(j, i, a[i][j]);
Label l1 = new Label(2, 0, "Result");
ws.addCell(l);
ws.addCell(l1);
}
}
for (int i = 1; i < s.getRows(); i++) {
selenium.type("Email", s.getCell(0, i).getContents());
selenium.type("Passwd", s.getCell(1, i).getContents());
selenium.click("signIn");
selenium.waitForPageToLoad("30000");
boolean aa = selenium.isTextPresent("The username or password you entered is incorrect. [?]");
System.out.println("the value of aa is::" + aa);
if (aa)
{
Label l3 = new Label(2, i, "fail");
ws.addCell(l3);
System.out.println("Login Failure");
Thread.sleep(10000);
} else {
Label l2 = new Label(2, i, "pass");
ws.addCell(l2);
selenium.click("link=Sign out");
Thread.sleep(10000);
}
}
wwb.write();
wwb.close();
}
@AfterClass
public void tearDown() throws Exception {
selenium.stop();
seleniumserver.stop();
}
}
Your input data should be like this....
Your out put excel should be like this

Write results to excel sheet


Write results to excel sheet

After successfully executing scripts, every one want to write results to excel sheet..here is the way to write results to excel
sheet....
Below is the sample script to write results to excel sheet...
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;
public class Importexport1 {
public Selenium selenium;
public SeleniumServer seleniumserver;
@BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://");
seleniumserver.start();
selenium.start();
}
@Test
public void testImportexport1() throws Exception {
// Read data from excel sheet
FileInputStream fi = new FileInputStream(
"F:\\Framework\\testdata\\Login1_Credentials.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
String a[][] = new String[s.getRows()][s.getColumns()];
// Write the input data into another excel file
FileOutputStream fo = new FileOutputStream(
"F:\\Framework\\Results\\LoginResult1.xls");
WritableWorkbook wwb = Workbook.createWorkbook(fo);
WritableSheet ws = wwb.createSheet("loginresult1", 0);
selenium.open("http://www.gmail.com");
selenium.windowMaximize();
System.out.println("s.getRows() = " + s.getRows());
for (int i = 0; i < s.getRows(); i++) {
System.out.println("s.getColumns = " + s.getColumns());
for (int j = 0; j < s.getColumns(); j++) {
a[i][j] = s.getCell(j, i).getContents();
Label l = new Label(j, i, a[i][j]);
Label l1 = new Label(2, 0, "Result");
ws.addCell(l);
ws.addCell(l1);
}
}
for (int i = 1; i < s.getRows(); i++) {
selenium.type("Email", s.getCell(0, i).getContents());
selenium.type("Passwd", s.getCell(1, i).getContents());
selenium.click("signIn");
selenium.waitForPageToLoad("30000");
boolean aa = selenium.isTextPresent("The username or password you entered is incorrect. [?]");
System.out.println("the value of aa is::" + aa);
if (aa)
{
Label l3 = new Label(2, i, "fail");
ws.addCell(l3);
System.out.println("Login Failure");
Thread.sleep(10000);
} else {
Label l2 = new Label(2, i, "pass");
ws.addCell(l2);
selenium.click("link=Sign out");
Thread.sleep(10000);
}
}
wwb.write();
wwb.close();
}
@AfterClass
public void tearDown() throws Exception {
selenium.stop();
seleniumserver.stop();
}
}
Your input data should be like this....

Your out put excel should be like this

Collection Java Programming Interview Questions 1

Collection API ?
Java Collections framework API is a unified architecture for representing and manipulating collections. All collections
frameworks contains interface, implementations and algorithms. Following are the benefits of collection framework.
Reduces programming efforts. - Increases program speed and quality.
Allows interoperability among unrelated APIs.
Reduces effort to learn and to use new APIs.
Reduces effort to design new APIs.
Encourages & Fosters software reuse.
Collection contains six interfaces.
Set, List and SortedSet: extends collection interface
Map and SortedMap : dont extend collection interface.a

What is HashMap and Map?


Maps stores key Value pair, and Hashmap is class that implements that using hashing technique.

Diff HashTable Vs HashMap Vs HashSet

Hashtable
Hashtable is basically a datastructure to retain values of key-value pair. Doesnot allow null for key and values
It is synchronized. So it comes with its cost. Only one thread can access in one time
Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on
a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

Hashtable<Integer,String> rank= new Hashtable<Integer,String>();

rank.put(1,"A");
rank.put(1,"B");
rank.put(1,"C");

rank.put(null,"E"); NullPointerException at runtime

System.out.println(rank.get(1));
System.out.println(rank.get(2));

HashMap
Like Hashtable it also accepts key value pair.Allows null values
It is unsynchronized. So come up with better performance
By using following command Hashmap can be synchronized.
Map m = Collections.synchronizedMap(hashMap);

HashMap<Integer,String> Lang= new HashMap<Integer,String>();

Lang.put(1, "java");
Lang.put(2, null);

HashSet
HashSet does not allow duplicate values.
It can be used where you want to maintain a unique list. You also use its contain method to check whether the object is already
available in HashSet.
It provides add method rather put method.

HashSet<String> str= new HashSet<String>();

str.add ("Apple");
str.add ("Boy");
str.add ("Cat");

if (str.contains("Apple"))

Iterator and implementation


An iterator is an object that enables a programmer to traverse a collection.
Iterator iter = list.iterator();
while (iter.hasNext()) {
System.out.print(iter.next());
if (iter.hasNext())
System.out.print(", ");
}

Diff Iterator Vs ListIterator


Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements
ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

Interface Implementation:

Implementations
Interface Array Balanced Tree Linked List Hash table
List ArrayList LinkedList
Map TreeMap HashMap
Set TreeSet HashSet
Deque ArrayDeque LinkedList

Collection interview Questions in Java 2

ArrayList vs LinkedList

Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for
LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements,
using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down
for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an
ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot
of editing in the middle of the list.

Array vs ArrayList vs LinkedList vs Vector in java

Array vs ArrayList:
ArrayList is much better than Array, when the size need to be increased dynamically. Efficiency is possible with arrays. ArrayList
permits null elements.
ArrayList has group of objects. Array it treated as an object.

LinkedList vs Vector:
A vector is a growable array which can store many objects of different classes.
A linked list is a linear list where each item has a link to the next item in the list. It can be used to implement queue or stack
operations.

ArrayList vs LinkedList
Array list is better than linked list for accessing elements.Linked list is better than array list to perform insertion and deletion
operations at arbitrary locations.

Vector Vs ArrayList
Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run
in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.
ArrayList has no default size while vector has a default size of 10.

What is an enumeration?
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is
obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the
collection. It allows sequential access to all the elements stored in the collection.
equals vs toString vs hashcod are methods in Object

Sort Diff b/w Arrays and Collections

Both use the same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a
translation of List to array. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is
done directly on the array.
Printing the Fibonacci Series using Java

public class FibonaciN {

public static void main(String args[])


{
int prev, next, sum, n;
prev=next=1;
for(n=1;n<=9;n++)
{
System.out.println(prev);
sum=prev+next;
prev=next;
next=sum;
}
}
}
Basic String Operations in Java

public class StringOperations {

public static void main(String args[]){


String str1="Hello";
String str2="Ja va";
String str3="Hello";

// String Operations

System.out.println("String1 == String3"+ str1.equals(str3));


System.out.println("String2 at Index 2:"+str2.charAt(2));
System.out.println("Compare Str2 and Str3"+str2.compareTo(str3));
System.out.println("Compare str1 and str3"+str1.compareTo(str3));
System.out.println("String2 contains Ja: "+str2.contains("Ja"));
System.out.println("String is empty ?"+str1.isEmpty());
System.out.println("Sting HashCode"+ str1.hashCode());
System.out.println("Substring of String1"+str1.substring(2, 3));
System.out.println("Remove whitespaces in String2"+str2.trim());
System.out.println("Convert to LowerCase"+str2.toLowerCase());
System.out.println("Replace a with A"+str3.replace('a','A'));
}
}

OutPut:
========
String1 == String3true
String2 at Index 2:
Compare Str2 and Str32
Compare str1 and str30
String2 contains Ja: true
String is empty ?false
Sting HashCode69609650
Substring of String1l
Remove whitespaces in String2Ja va
Convert to LowerCaseja va
Replace a with AHello
Palindrome in Java for Integers and Strings

public class JavaPalindrome {

public static void main(String arg[]){


int num=121;
String str="teet teet";
System.out.println("Given Number"+num+"is Palindrome:"+intPalindrome(num));
System.out.println("Given String"+str+"is Palindrome:"+stringPalindrome(str));
System.out.println("String reverse using toChar Array");
System.out.println("Given String"+str+"is Palindrome:"+stringCharArrayPalindrome(str));
}

private static boolean stringCharArrayPalindrome(String str) {


String rev="";
char arr[]=str.toCharArray();
for(int i=arr.length-1;i>=0;i--)
rev=rev+arr[i];
if(str.equalsIgnoreCase(rev))
return true;
else
return false;

private static boolean stringPalindrome(String st) {


String str1[]=st.split("");
String revstr="";
for(int i=str1.length-1;i>=0;i--){
revstr+=str1[i];
}
if(st.equalsIgnoreCase(revstr))
return true;
else
return false;
}

// Checking Number Palindrome or not


private static boolean intPalindrome(int num) {
int n = num;
int rev = 0;
for (int i = 0; i <= num; i++)
{
int r = num % 10;
num = num / 10;
rev = rev * 10 + r;
i = 0;
}

if (n == rev) {
return true;
} else {
return false;
}
}/** Number palindrome */

}
Polymorphism in Java Using Overloading and Overridden methods

Polymorphism
One form and many implementations.
It can be acheived by using inheritence,overloading and Overriding.
Compile time Polymorphism: Over loading
Runtitme Polymorphism: Over riding
Runtime Polymorphism /Dynamic method dispatch:
Its a process in which a call to an overridden methodis resolved at runtime rather than compile itme.
Dynamic Binding: Refers to linking of a procedure call to the code to be executed in response to the call
Also known as late binding :Code associated to procedure call is not known untile the time of the call at runtime.

Overloading.
Two or more methods with same name in the same class with different arguments.

Overloaded methods Must change the argument list


May change the return type
May change the access modifiers.
May change the checded exceptions.

Example:
package com.oops;

public class OverLoadingExample {

public int sum(int a,int b){


System.out.println("Int Int");
return a+b;
}

public double sum(double a,double b){


System.out.println("Double Double");
return a+b;
}

public int sum(int a,double b){


System.out.println("Int Double");
return (int) (a+b);
}
public static void main(String args[]){

OverLoadingExample oe=new OverLoadingExample();


System.out.println("Overloading method"+oe.sum(3, 7));
System.out.println("Overloading method"+oe.sum(2.5, 5.7));
System.out.println("Overloading method"+oe.sum(2, 5.5));
}
}

Output:
=======
Int Int
Overloading method10
Double Double
Overloading method8.2
Int Double
Overloading method7

Overriding:

Occurs in the subclass and declares method that has same type arguments as a method and declared by one of its super class.

It can be used for defining the behaviour of child class.


Argument list same as overriden method.
Constructors canot be overridden.
final methods canot be overridden.
Static method cannot be overridden but can be re-declared.
super() can be used for invoking parent class(Super class) methods.

Example
package com.oops;

class OverExample{

public void fun1(){


System.out.println("Super Function1");
}

public void fun2(){


System.out.println("Super Using super() Function2");
}

}
public class OverRiddingExample extends OverExample{

public void fun1(){


System.out.println("Subclass Function1");
}

public void fun2(){


super.fun2();
System.out.println("Subclass Function2");
}

public static void main(String[] args) {


OverExample or=new OverRiddingExample();
OverExample oe=new OverExample();
or.fun1();
oe.fun1();
or.fun2();
}

Output:
========

Subclass Function1
Super Function1
Super Using super() Function2
Subclass Function2
Inheritance in Object Orient Programming and Java

Inheritance
Its a process where one object acquire properites another.
Inheritence reduces the code re-usablity.

Inheritence can be achieved by using extends or implemnts keyword

Single Inheritance:
Class A extends B{
statements
}

Example:
=============
Pulsar is subclass of Bike
TVS is subclass of Bike.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){


System.out.println("Color: Red & Brand:Own");
}

}
public class SingleInheritence extends TwoWheeler {

public static void main(String args[]){


TwoWheeler two=new TwoWheeler();
SingleInheritence si=new SingleInheritence();

System.out.println(si instanceof TwoWheeler);


System.out.println("Calling method in SuperClass");
si.setProp();
}
}

Output
=======
true
Calling method in SuperClass
Color: Red & Brand:Own

Multiple Inheritance can be acheived by using interface.

Interface in Java Language (Click on link to know about interfaces)

Below example contains Single Inheritance and Multiple Inheritance Using Interfaces.

package com.oops;

class TwoWheeler{
int count=1;

public void setProp(){


System.out.println("Color: Red & Brand:Own");
}

interface Car
{
public void setBrandname(String name);
}

interface HeaveyVechile{

public void setProperites(String prop);


}

public class Wheeler extends TwoWheeler implements Car, HeaveyVechile{

public static void main(String args[]){

TwoWheeler two=new TwoWheeler();


Wheeler si=new Wheeler();

System.out.println(si instanceof TwoWheeler);


System.out.println("Calling method in SuperClass");
si.setProp();
si.setBrandname("First");
si.setProperites("HeavyLoadVechile");
}

@Override
public void setBrandname(String name) {
System.out.println("Brand name is"+name);

@Override
public void setProperites(String prop) {
System.out.println("Heavy Vechile with 4 or 8 Wheels "+prop);

Output
=========
true
Calling method in SuperClass
Color: Red & Brand:Own
Brand name isFirst
Heavy Vechile with 4 or 8 Wheels HeavyLoadVechile
interfaces in Object Oriented Programming Language
interface
==========
Descriptive set of methods. Implements class needs to be implemented methods in interface.

Properties of interface:
=========================
Canot mark interface as final
Cannot instiate interface.
Default: Methods in interface are abstract
fields in interface are static and final.
interface can implement class.
interface can extend multiple interfaces.

Class Implementing Interface


============================
package com.oops;

interface Bike{

//final static fields as default


int Capacity=150;

//abstract methods as default


public void speed();
public void price();
}
public class InterfaceExample implements Bike {

@Override
public void speed() {
System.out.println("Speed of Bike is 100 KMPH");

@Override
public void price() {
System.out.println("Price of Bike is 75K");

public static void main(String args[]){

InterfaceExample it=new InterfaceExample();


it.speed();
it.price();
}

Interface extends Multiple Interfaces

public interface Computer


{
public void setBrandname(String name);
}

public interface Desktop extends Computer


{
public void setProperty(String prop);
public void viewProperty(String id);
}

public interface Laptop extends Computer


{
public void setProcess(double process);
public void setScreen(int size);
}

public interface Laptop extends Computer,Device{

statements
}
Encapsulation in Java Programming

Encapsulation: is like information Hiding.


Hiding the properites and behaviors of object and allowing outside access via public methods.

Example for Encapsulation:


============================

EmpDetails.java:
package com.oops;

public class EmpDetails {

private int empid;


private String empname;

public void setEmpid(int id){


empid=id;
}

public int getEmpid(){


return empid;
}

public void setEmpName(String name){


empname=name;
}

public String getEmpName(){


return empname;
}
}

EncapsulationExample.java

package com.oops;

public class EncapsulationExample {

/**
* @param args
*/
public static void main(String[] args) {
EmpDetails emp1=new EmpDetails();
emp1.setEmpid(1);
emp1.setEmpName("First");

System.out.println("Employee details id: "+emp1.getEmpid()+" and name:"+emp1.getEmpName());

Output
==========
Employee details id: 1 and name:First
Java Exception Handling Programming Questions

Q) What are the two types of Exceptions?


A)Checked Exceptions and Unchecked Exceptions.

Q) What is the base class of all exceptions?


A) java.lang.Throwable

Q)If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B
which is a subclass of class A can throw IOException. If the above statement true?
A) The overriding method can not throw any checked exception other than the exception classes or sub-classes of those
classes which are thrown by the overridden method.
In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException
exception.

Q)Can we have a try block without a catch block?


public class JExample {

public static void main(String args[]){


int i=0;
int j=4;

try
{
int k=j/i;
}
finally{
System.out.println("finally");
}
}
}

Output:
=======
finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)

Q) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of
checked exception handling?
A) Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or
specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the
application like Network error, File Access Denied etc.
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array
element which doesnt exist.

Q)Explain try,catch and finally statements in Java ?


The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code.

try {

} catch (Exception e) {

}finally{

Example
======

public class JExample {

public static void main(String args[]){


int i=0;
int j=4;

try
{
int k=j/i;
}catch(Exception e)
{
System.out.println("Exception caught");
e.printStackTrace();
}
finally{
System.out.println("finally");
}
}
}

Output:
======
Exception caught
java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)
finally

Q) If there is common code to be executed in the catch block of 10 exceptions which are thrown from a single try block, then
how that common code can be written with minimum effort?
A) In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code.
In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. e.g.
catch(SQLException sqle | IOException ioe){}
4) Have you every created custom exceptions? Explain the scenario?
Ans: Custom exceptions are useful when the JDK exception classes dont capture the essence of erroneous situation which
has come up in the application. A custom exception can be created by extending any subclass of Exception class or by
implementing Throwable interface.

Q) What is the difference between Validation, Exception and Error?


A)Validation is the process of making user enter data in a format which the application can handle.
Exception handling is the process when the application logic didnt work as expected by the Java compiler.
Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory.
Q) What is the purpose of finally block? In which scenario, the code in finally block will not be executed?
A) finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The
kind of code written in a finally block consists of clean up code such as closing of database/file connection.
But JDK 7 has come up with try with resources block which automatically handles the closing of resources.

Q) Can a finally block exist with a try block but without a catch?
A)Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

Q) What is the difference between throw and throws?


Throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws
clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of
the method can guard against the exceptions.
Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma.
the statement would be as follows: public void doSomething() throws IOException,MyException{}

Q) How to create Custom Exception in Java?


package com.test;

//NullException is the user exception defined


class NullException extends Exception{

int a;

public NullException(int i) {
i=a;
}

public String toString(){


return "Created NullException:"+a;
}
}
public class CustomException
{

public static void Divide(int a,int b) throws NullException{

int k=a/b;
throw new NullException(k);
}
public static void main(String args[]){

try{

CustomException c=new CustomException();


c.Divide(5, 2);
}catch(Exception e){
System.out.println("Main CustomExceptionm:" +e);
}finally{
System.out.println("Finally Exceuting");
}

}
}

Output
=========
Main CustomExceptionm:Created NullException:0
Finally Exceuting

Q) What are the differences between NoClassDefFoundError and ClassNotFoundException?


A) NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while
executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script
deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
For example: The database driver is not found when trying to load the driver using Class.forName() method.

Q) Can a catch block exist without a try block?


A)No. A catch block should always go with a try block.

Q) What will happen to the Exception object after exception handling?


A)Exception object will be garbage collected.

Q)How does finally block differ from finalize() metho


Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected
method in the Object class which is called by the JVM just before an object is garbage collected.

Q) What is the purpose of throw keyword? What happens if we write throw null; statement in a Java program?
A) throw keyword is used to re-throw an exception which has been caught in a catch block. The syntax is throw e; where
e is the reference to the exception being caught. The exception is re-thrown to the client.
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword
is used.
The use of throw null; statement causes NullPointerException to be thrown.

Q) return statement in try,catch and finally ?


public class ExceptionDemo {

public int chkException(int arr[]){

int k=0;
int t=1,c=2,f=3;
try
{
for(k=0;k<5;k++)
System.out.println("arr Element"+arr[k]);
System.out.println("Try Catch");
return t;
}catch(Exception e){
System.out.println("Failed on exception"+e.getMessage());
System.out.println("Catch Retrun");
return c;
}finally{
System.out.println("Finally Return");
return f;
}
}

public static void main(String args[]){

int arr[]={1,4,5};

ExceptionDemo e=new ExceptionDemo();


e.chkException(arr);
}
}

Output
============
arr Element1
arr Element4
arr Element5
Failed on exception3
Catch Retrun
Finally ReturnThread Example in Java

public class ThreadExample extends Thread{

public synchronized void run(){


for(int i=0;i<11;i++)
System.out.print(i);
System.out.println(" ");
}
public static void main(String args[]){
Thread t1=new ThreadExample();
Thread t2=new ThreadExample();
Thread t3=new ThreadExample();

t1.start();
t2.start();
t3.start();

t1.setPriority(MAX_PRIORITY);
System.out.println("Thread 1 Priority"+t1.getPriority());

System.out.println("Thread 1 Group"+t1.getThreadGroup());

System.out.println("State of Thread2"+t2.getState());

}
}
Advantages and Disadvantages of selenium automation tool

Advantages of Selenium

1. Open Source
2. Supports all browsers like IE, Firefox, Mozilla, Safari
3. Supports all Operating Systems.
4. Supports all programming languages Java,Ruby,C# and Python.
5. Run multiple tests at a time.

Disadvantages

1. Identifying the locators that support common attributes like id, names etc as well as XPATH, javascript DOM
and others (Use firebug for finding the locators)
2. Detailed results are not available
3. Selenium IDE does not supports loop and data driven testing
4. No Option to verify the images.
5. Reading File in Java Using Java Programming
6.
package com.io;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileRead {

public static void main(String args[]){

try
{
String str;
FileInputStream in=new FileInputStream("C:\\Downloads\\FRead.txt.txt");
DataInputStream din=new DataInputStream(in);
BufferedReader br=new BufferedReader(new InputStreamReader(in));

while((str=br.readLine())!= null){
System.out.println(str);
}
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}

}
}
7.
8. Output:
9. ==========
10. Hi,
11. This is first file for reading
12. Thanks
13. Finding second largest element in array using java

public class SecondHighestElement {

public static void main(String args[]){

int a[]={1,2,46,672,24,5,6,46,672};

System.out.println("Second Highest Element"+secHighestElement(a));


}

private static int secHighestElement(int[] a) {


int first=0,second=0;

for(int i=0;i<a.length;i++){
if (first <a[i]){
second=first;
first=a[i];
}
if(second<a[i] && first!=a[i])
second=a[i];
}
return second;
}
}Finding duplicate elements in given array using Set

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class DuplicateNumbersInArray {

public static void main(String args[]){


int a[]={1,2,3,4,5,6,6,4,4,3,3};

System.out.println("Duplicate elements in Array"+dupElementsUsingSet(a));


}

private static ArrayList<Integer> dupElementsUsingSet(int[] a) {


ArrayList<Integer> arr=new ArrayList<Integer>();
Set<Integer> sortset=new HashSet<Integer>();
for(int i=0;i<a.length;i++){
if(sortset.contains(a[i]))
arr.add(a[i]);
else
sortset.add(a[i]);
}
return arr;
}
}
}selenium.start() - Takes you to the location where selenium server is and runs the server.
}selenium.open() - Takes you to the provied URL/Website address.
}selenium.getTitle() - Get the title of the current browser window.
}selenium.windowFocus() - Get the focus on the current window.
}selenium.windowMaximize() - Maximizes the current window.
}selenium.close() - Close the session
Selenium Interview Questions and Answers

Describe Selenium:
Selenium is an open source portable software testing framework for web based application.
Selenium provides IDE, a record and play back tool for web based application
RC and Web Driver support scripting in different languages like JAVA, PYTHON, RUBY, .Net
Grid supports testing of web based application on Client Server architecture supporting multiple browser on different machine
Selenium supports browsers: Firefox, Chrome, IE, Safari, Custom and many more.
The tests can be written as HTML tables or coded in a number of popular programming languages and can be run directly in most
modern web browsers.
Selenium operations are highly flexible, allowing many options for locating UI elements and comparing expected test results
against actual application behavior.
Selenium can be deployed on Windows, Linux, and Macintosh.
Selenium is used for UAT (User Acceptance Test), Functional Testing, Regression Testing
Selenium IDE is an integrated development environment for Selenium tests.
Operates as a Firefox add-on and provides an interface for developing and running individual test cases or entire test suites.
It also has a context menu (right-click) integrated with the Firefox browser, which allows the user to pick from a list of assertions
and verifications for the selected location.
Offers full editing of test cases.
Although it is a Firefox only add-on, tests created in it can also be run against other browsers by using Selenium-RC & specifying
the name of the test suite on the command line.
Components of Selenium:
IDE
Remote Control
Web Driver
Grid
IDE:
Record and playback
Intelligent field selection will use IDs, names, or XPath as needed
Auto complete for all common Selenium commands
Walk through test cases and test suites
Debug and set breakpoints
Save tests as HTML, Ruby scripts, or other formats
Support for Selenium user-extensions.js file
Option to automatically assert the title of every page
Rollup common commands

Remote Control (RC) and Web Driver:


Selenium-RC provides an API (Application Programming Interface) and library for each of its supported languages: HTML, Java, C#,
Perl, PHP, Python, and Ruby. Selenium-RC allows the test automation developer to use a programming language for maximum
flexibility and extensibility in developing test logic
Handling multiple frames, browsers, pop-ups and alerts
Page Navigation
Drag-and-drop
Ajax based UI Navigation
Grid:
Selenium-Grid allows the Selenium-RC solution to scale for test suites or test suites to be run in multiple environments
With Selenium-Grid multiple instances of Selenium-RC are running on various operating system and browser configurations, each
of these when launching register with a hub. When tests are sent to the hub they are then redirected to an available Selenium-
RC, which will launch the browser and run the test
Selenese Commands in Selenium:
clicking a link - click or clickAndWait commands
entering values - type command
selecting options from a drop-down listbox - select command
clicking checkboxes or radio buttons - click command
Test Runner:
Test Runner allows you to run the test case in a browser loaded with the Selenium-Core TestRunner. Test runner is invoked by
clicking the below Shown button in the IDE
Running Test Options:
Run a Test Case: Click the Run button to run the currently displayed test case.
Run a Test Suite: Click the Run All button to run all the test cases in the currently loaded test suite
Stop and Start: The Pause button can be used to stop the test case while it is running. The icon of this button then changes to
indicate the Resume button. To continue click Resume
Stop in the Middle: Set a breakpoint in the test case to cause it to stop on a particular command. This is useful for debugging your
test case. To set a breakpoint, select a command, right-click, and from the context menu select Toggle Breakpoint
Start from the Middle: We can set the IDE to begin running from a specific command in the middle of the test case. This also is
used for debugging. To set a start point, select a command, right-click, and from the context menu select Set/Clear Start Point
Run Any Single Command: Double-click any single command to run it by itself. This is useful when writing a single command. It lets
you immediately test a command you are constructing, when you are not sure if it is correct. You can double-click it to see if it
runs correctly. This is also available from the context menu

Assertion Statements:
1. Assert command will fail and abort current execution

2. Verify command will fail and continue current execution

assertTextPresent : This will assert if the text is present in the page


assertText: This will assert if a particular element is having the particular text
assertTitle: This will assert if the page is having a proper title
assertValue: This will assert if a Text box or check box has a particular value
assertElementPresent: This will assert if a particular UI Element is present in the page
WaitFor Command:
waitForPageToLoad : This command will make the script to wait till the page loads. Syntax is waitForPageToLoad(timeout); Time
out is the maximum time the script will wait for the page to load
waitForAlert : This command will wait for the alert message to appear
waitForTable: This command will wait for the Web table to completely load in the page
waitForTitle: This command will for the page Title to appear on the browser
Other waitFor commands : Selenium has several other wait command like waitForText,waitForPopup and so on. These commands
are generically called Synchronization commands
Advantages:
Support multiple landguages - C#, Java, PHP, Perl, Phython
Supported on multiple OS - Windows, Linux and Mac OS
Highly active developer community - backed by Google
Powerful methods to locate elements (Xpath, CSS, DOM)
Disadvantages:
Challenges running on browsers other than Firefox
Difficulty to automate AJAX
Limitations to automate Applets, MS and Desktop Applications

I have been think to post Selenium webdriver example for a long time. This is my first post on Selenium Webdriver. I have
mentioned the steps to create a project in eclipse and run the sample webdriver code with TestNG.

I have provide the sample code to test the Gmail login functionality. Please do the setup in Eclipse and Run it in TestNG.

1. Setting up New Project in Eclipse

1.1 Create a new Java Project

1.2 Save the new project and view the project in eclipse work space

1.3 Create a new Folder for library files and download all the java webdriver jar files. Copy the jar files from libs folder also
Download: http://selenium.googlecode.com/files/selenium-java-2.19.0.zip

1.4 Configure the build Path

Right click on the Project name -> Build Path -> Configure Build Path

Add Jars -> Select all the Jars from the Lib folder and add it. .

1.5 Create new Package under the src folder


1.6 Create a new java file

2. Copy and paste the below code

?
1 package com.test.webdriver;
2
3 import static org.testng.AssertJUnit.assertEquals;
4
5 import org.openqa.selenium.By;
6 import org.openqa.selenium.WebDriver;
7 import org.openqa.selenium.firefox.FirefoxDriver;
8 import org.testng.annotations.AfterClass;
9 import org.testng.annotations.BeforeClass;
10 import org.testng.annotations.Test;
11
12 public class Driver {
13 private WebDriver driver;
14
15 @BeforeClass
16 public void Startup(){
17 driver = new FirefoxDriver();
18 }
19
20 @Test (description="Google Login")
21 public void GoogleLogin() throws Exception{
22 driver.get("http://www.gmail.com");
23 assertEquals("Sign in", driver.findElement(By.id("signIn")).getAttribute("value"));
24 driver.findElement(By.id("Email")).sendKeys("*********");
25 driver.findElement(By.id("Passwd")).sendKeys("**********");
26 driver.findElement(By.id("signIn")).click();
27 Thread.sleep(10000);
28 driver.switchTo().frame("canvas_frame");
29 driver.findElement(By.id("gbgs4dn")).click();
30 driver.findElement(By.id("gb_71")).click();
31 driver.switchTo().defaultContent();
32 assertEquals("Sign in to Gmail", driver.findElement(By.id("button")).getText());
33 }
34
35 @AfterClass
36 public void teardown(){
37 driver.quit();
38 }
39
40 }

3. Run the Java Code as TestNG test

4. View the Emailable Report in TestNG output folder


Hope this help in developing the Selenium webdriver for beginners. For any questions post your comments here. I will try to solve
your problem.

How to create test suite using Junit and eclipse in selenium


There are some scenarios where we need to run multiple test cases. Either we can run those test cases independently or
together. But there are some real time cases where we need to run our test cases in a particular order. In this case we would
prefer Test Suite to combine the test cases together and decide their orders and run those.

Below are the steps

1. Create a Test Suite class where we create the Test Suites which will call all the test cases in a particular order.

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

public class TestSuite1 extends TestCase {

public static Test suite()


{
TestSuite suite = new TestSuite();

suite.addTestSuite( TestCase1.class);
suite.addTestSuite( TestCase2.class);
suite.addTestSuite( TestCase3.class);
return suite;
}

public static void main(String arg[])


{
TestRunner.run(suite());

}
}

Step 2. Create your first test case

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase1 extends SeleneseTestCase{

Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;

public void setUp() throws Exception {

RemoteControlConfiguration rc = new RemoteControlConfiguration();


rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();

}
public void testgoogling() {
selenium.open("/");
selenium.type("q", "Niraj");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Niraj"));

public void tearDown() throws InterruptedException{


selenium.stop();
seleniumServer.stop();
}
}

Step 3. Create your second test case

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase2 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {

RemoteControlConfiguration rc = new RemoteControlConfiguration();


rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}

public void testgoogling() {


selenium.open("/");
selenium.type("q", "Niraj Kumar");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Niraj Kumar"));

public void tearDown() throws InterruptedException{


selenium.stop();
seleniumServer.stop();
}
}

Step 4. Create your third test case


import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase3 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {

RemoteControlConfiguration rc = new RemoteControlConfiguration();


rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}

public void testgoogling() {


selenium.open("/");
selenium.type("q", "http://www.automationtricks.blogspot.com");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("http://www.automationtricks.blogspot.com"));

public void tearDown() throws InterruptedException{


selenium.stop();
seleniumServer.stop();
}
}

Step 5. Run your Test Suite


Go to your Test Suite class and right click on that and run as Junit Test.

This will run the TestCase1 then TestCase2 then TestCase3

If you want to execute your test cases in some specific order then you call them in that order like.

suite.addTestSuite( TestCase3.class);
suite.addTestSuite( TestCase2.class);
suite.addTestSuite( TestCase1.class);

Above will run the TestCase3 first then TestCase2 then TestCase1.

Introduction to Selenium WebDriver


Selenium WebDriver lets you write code to perform automated tests of web pages. UnlikeSelenium IDE (which records clicks
that you perform in the browser and plays them back), WebDriver requires you to write code to connect to the API which
controls the browser. The code can be written in Java, C# or a few other languages.

The Selenium WebDriver documentation has some good instructions, but while following them, I ran into a few hitches, but
was able to find the answers I needed from other pages on the internet. Hopefully I have referenced those other pages
correctly.
Obtaining Selenium WebDriver for Use with Java
1. Install Apache Maven. This will be used for downloading a project that can be imported into Eclipse or
NetBeans.
2. Create the pom.xml file shown on the WebDriver documentation page.
o Make sure to update the XML file with any potentially updated information on the Maven Download page.
3. Add the Maven installation directory to your PATH.
4. In the command prompt, navigate to the directory where you put the pom.xml file.
5. Run this command: mvn clean install (As shown in the WebDriver Documentation)
6. If you get an error about JAVA_HOME not being set, then:
1. Install the Java Development Kit. (You need the JDK, not just the JRE. Thanks Atlassian for the
clarification!)
2. Add a JAVA_HOME variable to your system environment variables. Make sure it points to the
home directory of where you installed the JDK.
3. If you still get the same error, restart your computer and run the command again. (Thanks
Michael Nesterenko's for your response at Stack Overflow for the idea of restarting the machine.)
7. If the command runs successfully, you should now have a folder called "target" that was created in the
same folder as your pom.xml file.
Setting up a Selenium WebDriver Project for Java in Eclipse

1. Use MVN to create an Eclipse project in by running this command in the same folder as your pom.xml
file: MVN eclipse:eclipse (as seen in these instructions.)
2. Import the project into Eclipse. See instructions.
3. If your project has errors about the M2_REPO classpath variable being missing.
o Add M2_REPO as a classpath variable in Eclipse and point it to your Maven repository folder on your
computer.
o Instructions for finding the Maven repository folder on your computer.
o Instructions for adding the M2_REPO classpath variable in Eclipse.
4. Your project should have no errors at this point.
5. Add a new class to your project, with a static main method.
6. Run your application to see if it will even run.
7. If you get the error: "Editor does not contain a main type", then:
o You need to tell Eclipse where the Source is for your project. (For instructions, refer to Dave McQueen's
response on CodeRanch on May 22, 2009.)
8. Your empty application should at least run at this point.
9. In the main() method, write your test code. Refer to this example Selenium WebDriver code.
10. If you are using the Firefox driver in your code, then do the following before running, or you will get an
error:
o Make sure Firefox is installed.
o Add the path to Firefox in your system's environment path variable.
o Restart Eclipse
11. If you are using the Internet Explorer driver in your code, then do the following before running or you will
get an error:
o Make sure to download and unzip The Internet Explorer Driver Server on your machine.
o Add the path to it in your system's environment path variable.
o Restart Eclipse.
12. If you are using the Chrome driver in your code, then do the following before running or you will get an
error:
1. Download and unzip the Chrome driver.
2. Add the path to it in your system's environment path variable.
3. Restart Eclipse.
13. Run your application.
14. Assuming you have an actual test script set up in your code, Firefox or Internet Explorer (depending on
which browser driver you used in your code) should launch at this point and the test should be performed
automatically.
Introduction
Selenium is a popular framework for testing the user interface (UI) of a web application. It is an extremely powerful tool for
running end-to-end functional tests. You can write tests in several programming languages and Selenium executes them into
one or multiple browsers.
Selenium, hereafter called Selenium 1, is not the only tool able to automate functional tests in a browser. WebDriver, created
by Simon Stewart (from Google), is a project with a similar goal. To control the browser, WebDriver relies on independent
clients using native support. WebDriver offers only Java bindings and does not support the same number of browsers as
Selenium 1.
Selenium 1 + WebDriver = Selenium 2
Selenium 1 and WebDriver merged to produce a better productSelenium 2, or Selenium WebDriver, which was released in
2011. Selenium 2 has the clean and object-oriented APIs from WebDriver and interacts with browsers in the best way possible
for that browser. Selenium 2 does not use a JavaScript sandbox, and it supports a wide range of browsers and multiple language
bindings. At the time of this writing, Selenium 2 provides drivers for:
Mozilla Firefox
Google Chrome
Microsoft Internet Explorer
Opera
Apple iPhone
Android browsers
With Selenium 2, you can write tests in Java, C#, Ruby, and Python. Selenium 2 also offers a headless driver based on HtmlUnit,
which is a Java framework for testing web applications. HtmlUnit is really fast, but it is not realistic as a driver associated with a
real browser.
At the moment, Selenium 2 is still under development as minor issues are being resolved. The current version is 2.9. Drivers for
Safari and Blackberry should be integrated in the near future.
In this article, learn how to use Selenium 2 to test web applications. Examples show how to remotely implement tests. Learn
also how to move your written tests from Selenium 1 to Selenium 2.
Download the source code used in this article.
Back to top
Getting started with Selenium 2
In this section, learn how to use the Selenium 2 framework for a relatively simple test of a web application. Java is the language
for the development environment. You need the selenium-java-<version>.jar containing the Java binding (see Resources to
download). In a Maven project, you just need to include the right dependency in your pom.xml, as shown in Listing 1.

Listing 1. Selenium-java dependency

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.9.0</version>
</dependency>

Now you can start writing tests. The main component in the WebDriver API is the WebDriver interface. There is an
implementation of this common interface for each browser available. For instance, the FirefoxDriver class will take care of
controlling Mozilla Firefox. Listing 2 shows how to instantiate a specific implementation inside your test. You can use the test
framework that best suits your needs, such as JUnit or TestNG.

Listing 2. FirefoxDriver instantiated

public class Selenium2Example1Test {


@Test
public void test() {
// Instantiate a webDriver implementation
WebDriver webdriver = new FirefoxDriver();
}
}

To load the page to test, use the get() method. In Listing 3, the GitHub homepage (https://github.com) is loaded into the Firefox
instance created previously.

Listing 3. Load the page under test

WebDriver webdriver = new FirefoxDriver();


webdriver.get(https://github.com);

You can now make some assertions on the page just loaded. Suppose you want to test that the page title is equal to "GitHub -
Social Coding", as in Listing 4. WebDriver offers the getTitle() method; you can leverage the chosen testing framework to make
an assertion.

Listing 4. Assertion on the page title

Assert.assertEquals("GitHub - Social Coding", webdriver.getTitle());

After you finish the test, it's a good practice to kill the WebDriver instance using the quit() method, as shown in Listing 5.

Listing 5. Killing the WebDriver instance

webdriver.quit();

FirefoxDriver is just one of the WebDriver implementations available. You could execute the same test using the ChromeDriver
to run the test inside Chrome. Listing 6 shows the full example using the ChromeDriver.

Listing 6. ChromeDriver sample

public class Selenium2Example2Test {


@Test
public void test() {
System.setProperty("webdriver.chrome.driver",
"src/main/resources/drivers/chrome/chromedriver-mac");

// Instantiate a webDriver implementation


WebDriver webdriver = new ChromeDriver();

webdriver.get(https://github.com);

Assert.assertEquals("GitHub - Social Coding", webdriver.getTitle());


}
}

Before instantiating the ChromeDriver, you need to set the "webdriver.chrome.driver" system property. This property points to
the location of the ChromeDriver file for your OS (see Resources to download). The example in Listing 6 uses the version for the
Mac; versions for Windows and Linux are also available.
To execute the same test inside Internet Explorer, you need to use an instance of the InterentExplorerDriver class, as shown in
Listing 7.
Listing 7. InternetExplorerDriver instantiation

WebDriver webdriver = new InternetExplorerDriver();

When using InterenetExplorerDriver, you might encounter a security issue saying: "Protected Mode must be set to the same
value (enabled or disabled) for all zones." To overcome the problem, you can set a specific capability, as shown in Listing 8.

Listing 8. Security capability set for Internet Explorer

DesiredCapabilities capability=DesiredCapabilities.internetExplorer();
capability.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_
IGNORING_SECURITY_DOMAINS, true);
WebDriver webdriver = new InternetExplorerDriver(capability);

To execute a test inside Opera, you need to instantiate the OperaDriver class, which was developed directly by Opera.
Remember to include the JAR containing the driver inside your project. If you're using Maven, you just need to add the
dependency in Listing 9.

Listing 9. OperaDriver dependency

<dependency>
<groupId>com.opera</groupId>
<artifactId>operadriver</artifactId>
<version>0.7.3</version>
</dependency>

Additional configurations are required to run the tests inside an iPhone or Android browser emulator.
Back to top
Testing with Selenium 2
With Selenium 2, you can build tests that are more complex than those in the previous section. In this section, you'll test that
the top navigation in the GitHub homepage has five list items: Signup and Pricing, Explore GitHub, Features, Blog, and Login.
Figure 1 shows the Github homepage.

Figure 1. Github homepage


Review the HTML code behind the top navigationshown in Listing 10.

Listing 10. HTML code behind the top navigation

<html>
<head>
...
</head>
<body class="logged_out env-production">
<div id="main">
<div id="header" class="true">
...
<div class="topsearch">
<ul class="nav logged_out">
<li class="pricing">
<a href="https://github.com/plans">Signup and Pricing</a>
</li>
<li class="explore">
<a href="https://github.com/explore">Explore GitHub</a>
</li>
<li class="features">
<a href="https://github.com/features">Features</a>
</li>
<li class="blog">
<a href="https://github.com/blog">Blog</a>
</li>
<li class="login">
<a href="https://github.com/login">Login</a>
</li>
</ul>
</div>
...
</div>
...
</div>
...
</body>
</html>

You can leverage the WebDriver API to retrieve, from inside the HTML code, the elements you need to test.
The findElement()and findElements() methods return an instance or a list of instances, of the common interface WebElement.
The WebElementinterface, in a clean and object-oriented manner, is used for all of the elements in a page. There are different
strategies used in the API to locate a UI element. The strategies are represented by the different types of parameters passed
into thefindElement() and findElements() methods. Listing 11 shows the different strategies adopted through the different
methods applied to the abstract class By.

Listing 11. Using the findElement() method

WebElement element1 = webdriver.findElement(By.id("header"));


WebElement element2 = webdriver.findElement(By.name("name"));
WebElement element3 = webdriver.findElement(By.tagName("a"));
WebElement element4 = webdriver.findElement(By.xpath("//a[@title='logo']"));
WebElement element5 = webdriver.findElement(By.cssSelector(".feautures"));
WebElement element6 = webdriver.findElement(By.linkText("Blog"));
WebElement element7 = webdriver.findElement(By.partialLinkText("Ruby"));
WebElement element8 = webdriver.findElement(By.className("login"));

Using one of the strategies in Listing 11, you can start writing the test to retrieve the first elements: the LI tags inside the UL tag
with the nav class. Listing 12 uses Xpath (By.xpath()).

Listing 12. Xpath

List<WebElement> webElements = webdriver.findElements(By


.xpath("//ul[@class='nav logged_out']/li"));

Listing 13 uses CSS selectors (By.cssSelector()) to retrieve the LI tags.

Listing 13. CSS selector

List<WebElement> webElements = webdriver.findElements(By


.cssSelector("ul.nav li"));

At this point, you can make the first assertion on the number of items retrieved, as shown in Listing 14.

Listing 14. Assertion on the number of items

Assert.assertEquals(5, webElements.size());
The previous step verified that the number of LI tags is equal to five.
The next step is to retrieve each anchor (A tag) inside each LI tag. Listing 15 shows how to get the anchor inside the first LI. The
tagName (By.tagName()) strategy is used for this case.

Listing 15. Retrieving A anchor inside the first LI tag

WebElement anchor1 = webElements.get(0).findElement(By.tagName("a"));

In a similar fashion, you can collect all five anchors, as shown in Listing 16.

Listing 16. Retrieving all the anchors inside LI tag

WebElement anchor1 = webElements.get(0).findElement(By.tagName("a"));


WebElement anchor2 = webElements.get(1).findElement(By.tagName("a"));
WebElement anchor3 = webElements.get(2).findElement(By.tagName("a"));
WebElement anchor4 = webElements.get(3).findElement(By.tagName("a"));
WebElement anchor5 = webElements.get(4).findElement(By.tagName("a"));

At this stage, you can verify if the text inside the anchors corresponds to the expected string. To retrieve the text inside a tag,
WebDriver provides the getText() method. Listing 17 shows the full test method, with the assertions at the bottom of the test.

Listing 17. Complete test

@Test
public void test() {
WebDriver webdriver = new FirefoxDriver();
webdriver.get("https://github.com");
List<WebElement> webElements = webdriver.findElements(By
.xpath("//ul[@class='nav logged_out']/li"));
Assert.assertEquals(5, webElements.size());

// Retrieve the anchors


WebElement anchor1 = webElements.get(0).findElement(By.tagName("a"));
WebElement anchor2 = webElements.get(1).findElement(By.tagName("a"));
WebElement anchor3 = webElements.get(2).findElement(By.tagName("a"));
WebElement anchor4 = webElements.get(3).findElement(By.tagName("a"));
WebElement anchor5 = webElements.get(4).findElement(By.tagName("a"));

// Assertions
Assert.assertEquals("Signup and Pricing", anchor1.getText());
Assert.assertEquals("Explore GitHub", anchor2.getText());
Assert.assertEquals("Features", anchor3.getText());
Assert.assertEquals("Blog", anchor4.getText());
Assert.assertEquals("Login", anchor5.getText());

webdriver.quit();

After launching this test, a new Firefox window will open and stay open until all of the assertions are executed.
Back to top
Testing remotely with Selenium Grid 2
You can either locally or remotely run tests in Selenium 2. To run remotely, the tests need to use a specific implementation of
theWebDriver interface called RemoteWebDriver. You can specify the browser to be run using the DesiredCapabilities class.
Listing 18 shows an example.

Listing 18. RemoteWebDriver and DesiredCapabilities classes

DesiredCapabilities capabilities = new DesiredCapabilities();


capabilities.setBrowserName("firefox");
capabilities.setVersion("7");
capabilities.setPlatform("MAC");
WebDriver webdriver = new RemoteWebDriver(capabilities);

With the DesiredCapabilities class, you can specify the browser name, the platform, and browser version. You can also specify
many other capabilities the browser can support.
If you want to remotely execute structured tests and run multiple browsers (and possibly various virtual machines), Selenium
Grid offers a good solution.
Selenium Grid 2 provides an infrastructure where each node representing a different browser registers itself against a hub.
Singular tests will invoke a hub, which is in charge of dispatching each request to the right browser. Hub and nodes can run on
different virtual machines.
To test remotely, you'll need to download selenium-server-standalone-<version>.jar on each machine you're going to use. To
install a hub on a machine, go into the folder where you downloaded the required JAR and launch the command in Listing 19.

Listing 19. Starting the hub

java -jar selenium-server-standalone-2.9.0.jar ?role hub

You can access the Selenium Grid 2 console at http://localhost:4444/grid/console, where all the nodes available will be listed.
To register a node, simply launch a command, as shown in Listing 20.

Listing 20. Node registered against the hub

java -jar selenium-server-standalone-2.9.0.jar


-role webdriver ?hub http://localhost:4444/grid/register -port 5556

The command in Listing 20 registers, by default, seven browsers: five Firefox instances, one Chrome instance, and one Internet
Explorer instance. You can target a specific browser on a specific port, as demonstrated in Listing 21.

Listing 21. Firefox 7 instance registered on the hub

java -jar selenium-server-standalone-2.9.0.jar -role webdriver


-hub http://localhost:4444/grid/register -port 5556 -browser
browserName=chrome,version=14,platform=MAC

After registering a few browsers, the Selenium Grid 2 console should look like Figure 2.

Figure 2. Selenium Grid 2 console view


To use the grid, you need to specify inside your test cases the URL of the hub and the browser you want to control. Listing
22shows where the constructor of the RemoteWebDriver class accepts the URL of the hub and an instance
ofDesiredCapabilities defining the specific browser.

Listing 22. RemoteWebDriver instantiation

DesiredCapabilities capability = new DesiredCapabilities();


capability.setBrowserName("chrome");
capability.setVersion("14");
capability.setPlatform(Platform.MAC);
WebDriver webdriver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
capability);

In this case, the hub will launch the node associated to Chrome, Version 14 (previously registered in Listing 21).
Selenium Grid 2 is also backward compatible with Selenium 1. You can register Selenium 1 RC nodes (part of the Selenium 1
infrastructure) against the hub, as shown in Listing 23.

Listing 23. Selenium 1 RC node registration

java ?jar selenium-server-standalone-2.9.0.jar


-role rc ?hub http://localhost:4444/grid/register -port 5557

Back to top
Migrating tests to Selenium 2 from Selenium 1
If you need to migrate written tests from Selenium 1 to Selenium 2, the transition is quite smooth. The Selenium 1 APIs are kept
underneath the new APIs, making Selenium 2 completely backward compatible.
It's easy to convert your test from Selenium 1 into Selenium 2 thanks to the WebDriverBackedSelenium class. It takes an
instance of a WebDriver and the URL under test as parameters, and it returns a Selenium instance. Listing 24 shows the same
example as in Listing 16 but using the Selenium 1 API integrated in Selenium 2.

Listing 24. Selenium 1 integrated in Selenium 2

@Test
public void test() {
String url = "https://github.com";
WebDriver webdriver = new FirefoxDriver();
webdriver.get(url);
Selenium selenium = new WebDriverBackedSelenium(webdriver, url);
selenium.open(url);

// Get the number of LIs


Number lis = selenium.getXpathCount("//ul[@class='nav logged_out']/li");

Assert.assertEquals(5, lis.intValue());

// Retrieve the text inside the anchors


String anchor1Text = selenium.getText("//ul[@class='nav logged_out']/li[1]/a");
String anchor2Text = selenium.getText("//ul[@class='nav logged_out']/li[2]/a");
String anchor3Text = selenium.getText("//ul[@class='nav logged_out']/li[3]/a");
String anchor4Text = selenium.getText("//ul[@class='nav logged_out']/li[4]/a");
String anchor5Text = selenium.getText("//ul[@class='nav logged_out']/li[5]/a");

Assert.assertEquals("Signup and Pricing", anchor1Text);


Assert.assertEquals("Explore GitHub", anchor2Text);
Assert.assertEquals("Features", anchor3Text);
Assert.assertEquals("Blog", anchor4Text);
Assert.assertEquals("Login", anchor5Text);

webdriver.quit();
}

Selenium 2 has an increased focus on developers. It has a cleaner API than Selenium 1, as evidenced by
the getText() andgetXpathCount() method signatures. The Selenium 2 API is also more object-oriented. For example, you are
not allowed to deal with UI element objects, only strings.

SELENIUM WEBDRIVER TIPS & TRICKS


Written by Vadim Chadyuk | Friday, 20 April 2012
Print
Email
Add new comment
Rate this item

5
(3 votes)

verifyTextPresent for Selenium WebDriver


There is no method verifyTextPresent in Selenium WebDriver, so if you need to check text on the page, you can use the
following methods:

public boolean verifyTextPresent(String text){


return driver.getPageSource().contains(text);
}
or
public boolean verifyTextPresent(String text){
return driver.findElement(By.tagName("body")).getText().contains(text);
}

Working with frames


To work with frames, you can use the following methods.

I recommend the following method:

WebElement myFrame = driver.findElement(By.name("iframe_canvas"));


driver.switchTo().frame(myFrame);

You can switch to a frame by name:

driver.switchTo().frame("frame")

As well as by index:

driver.switchTo().frame(0);

Working with windows


To work with windows, I recommend using the following method:

public void switchToWindow(int numberWindow) {


String handle = driver.getWindowHandles().toArray()[numberWindow].toString();
driver.switchTo().window(handle);
}
Use the implicit waiting
I recommend always include implicit waiting, where they are not needed, just turn them off.
public void turnOnImplicitlyWait (int timeout) {
driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
public void turnOffImplicitlyWait () {
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
}

Using Drag and Drop


Drag and Drop is performed in that way:

Actions builder = new Actions(driver);


Action dragAndDrop = builder.clickAndHold(someElement)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();

Files uploading
If you have a file upload field (<input type=file>), then implement a file download in the following way:

fileInput.sendKeys(file);
HOW TO INTEGRATE SIKULI SCRIPT WITH SELENIUM WEBDRIVER
Posted on Apr 19, 2013 by Roman
Sikuli is a robust and powerful tool to automate and tests user interfaces screenshots. The core of Sikuli Script is written in Java,
which means you can use Sikuli Script as a standard JAVA library in your program. This article lets you know how to do that.
Sikuli is a robust and powerful tool to automate and tests user interfaces screenshots. The core of Sikuli Script is written in Java,
which means you can use Sikuli Script as a standard JAVA library in your program. This article lets you know how to do that.

1. Download and install Sikuli using the self-extracting installer(http://www.sikuli.org/download.html).


Note: Only 32-bit version is provided for using as a standard JAVA library. But SIKULI IDE could run on both 32-bit and 64-bit
Windows systems.

2. Create new Java project (use Eclipse as an example):


3. Fill project name and click Finish:
4. Create new class:
5. Fill class name and click Finish:
6. Include sikuli-script.jar, selenium-server-standalone-2.25.0.jar, selenium-java-2.25.0.jar in the CLASSPATH of your Java
project.
Get sikuli-script.jar from your Sikuli IDE installation path.
Sikuli Script is packed in a JAR file - sikuli-script.jar. Depending on the operating system you use, you can find the sikuli-script.jar
in according places.

Windows, Linux: Sikuli-IDE/sikuli-script.jar


Mac OS X: Sikuli-IDE.app/Contents/Resources/Java/sikuli-script.jar

After adding sikuli-script.jar, selenium-server-standalone-2.25.0.jar, selenium-java-2.25.0.jar as a libraries into your project, the
project hierarchy should look like this:
After click OK:

7. After configuring in build path, create and initialize an instance of Screen object.

SIKULI + SELENIUM WEBDRIVER

import org.junit.Test;
import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.sikuli.script.App;

import org.sikuli.script.FindFailed;

import org.sikuli.script.Pattern;

import org.sikuli.script.Screen;

public class sikuliFirstTest {

@Test

public void functionName() throws FindFailed {

// Create a new instance of the Firefox driver

WebDriver driver = new FirefoxDriver();

// And now use this to visit Google

driver.get("http://www.google.com");

//Create and initialize an instance of Screen object

Screen screen = new Screen();


//Add image path

Pattern image = new Pattern("C:\\searchButton.png");

//Wait 10ms for image

screen.wait(image, 10);

//Click on the image

screen.click(image);

Here example using SIKULI without Selenium WebDriver:

import org.junit.Test;

import org.sikuli.script.App;

import org.sikuli.script.FindFailed;

import org.sikuli.script.Pattern;

import org.sikuli.script.Screen;

public class sikuliFirstTest {


@Test

public void functionName() throws FindFailed {

//Open FireFox application with google home page

App firefox = App.open("c:\\Program Files\\MozillaFirefox\\firefox.exe");

//Create and initialize an instance of Screen object

Screen screen = new Screen();

//Add image path

Pattern image = new Pattern("C:\\searchButton.png");

//Wait 10ms for image

screen.wait(image, 10);

//Click on the image

screen.click(image);

//Close firefox

firefox.close();
}

}
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 = "example@yahoo.co.uk";
public static final String HOTMAIL_EMAIL = "example@hotmail.co.uk";

@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]//textarea")));

//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")).getText(), "Your message has been sent");
}

Selenium and Webdriver


Here is a simple program that shows how to use selenium.
More concrete examples of webdriver/selenium and page-objects are at http://code.google.com/p/java-through-
examples/source/browse/tests/org/megha/blog/example/selenium/

package org.megha.blog.example.selenium;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
/**
* Searches for a given string on yahoo.com.
* (just an example to show how selenium client is used.)
*/
public class YahooSearch {
// searches for the given string and prints the top two results
public void searchFor(String string) {
Selenium selenium = new DefaultSelenium("LOCALHOST", 4444, "*firefox", "http://www.yahoo.com/");
selenium.start();
selenium.open("/");
selenium.waitForPageToLoad("30000");
selenium.type("name=p", string);
selenium.click("id=search-submit");
selenium.waitForPageToLoad("30000");
// TODO: do something with the results
selenium.close();
selenium.stop();
}

public static void main(String[] args) {


YahooSearch search = new YahooSearch();
search.searchFor("google");
}
}

To start with WebDriver we need to learn about some of the useful APIs that are provided for automating user actions on an
application.

Let us list some of the actions that we need to automate while automating a test case:

1. Click a link, button


2. Type value in an Edit box
3. Select a value from the dropdown
4. Check / Uncheck a checkbox
5. Select a radio button
This is exactly what I am going to discuss in this post.

Click a link / button:


To click on an object through webdriver first we need to find out which locator we are going to use. Is it ID, name, xpath, or
css? For this purpose we can utilize firebug / xpath checker to find out is there any id / name exists for the object we are going
to perform action upon. Then write the code as below:

driver.findElement(By.xpath("//a[@href='CustomerInfo.htm']")).click();
In the above line of code driver could be FirefoxDriver, InternetExplorerDriver, ChromeDriver, HtmlUnitDriver, etc. On one of
these browsers we are going to find an element and then click as per the code.

findElement is an API provided by the webdriver which requires argument By.xpath. The xpath can be replaced by one of
the below methods if we need to identify the element with any other attributes such as css, name, classname, etc:

1. className
2. cssSelector
3. linkText
4. name
5. partialLinkText
6. tagName
7. xpath
8. id
To understand the above methods one needs the basic understanding of the HTML. Id, name, input, type, a, etc are the HTML
tags / attributes. Using these HTML tags and attributes xpath can be constructed and this I have already explained in one of
my earlier posts (How to write xpath)
Type value in an Editbox
Have a look at the below line of code.

driver.findElement(By.name("FirstName")).sendKeys("Google");
Here the webdriver finds the object first with findElement API and then keys in the value with sendKeysmethod.
Select a value from the dropdown
To select a value from a dropdown, follow the below steps:

1. Declare a List and assign all the values of dropdown using findElements method
2. Use a for loop to go through the elements one by one
3. Using an IF condition match the required option
4. Click the required option (.setSelected is deprecated)
Use the below code and put that into a function which does the job.

public static void selectValue(String valToBeSelected){

List <WebElement> options = driver.findElements(By.tagName("option"));

for (WebElement option : options) {


if (valToBeSelected.equalsIgnoreCase(option.getText())){

option.click();

call the static method wherever necessary selectValue(Texas) will select the value Texas from the dropdown country.
Check / Uncheck a checkbox
To Check / Uncheck a checkbox, the object needs to be identified using findElement method and then just click. To find out
whether the checkbox is checked or not utilize the method element.isSelected()

WebElement kancheck = driver.findElement(By.name("kannada"));

kancheck.click();

System.out.println(kancheck.isSelected());

Above code snippet will first click the checkbox named kannada and then verifies whether it is clicked or not.
Select a radio button
Follow the same steps which are used in Checkbox to select a radio button and then verify the status using isSelected() method.

WebElement gender = driver.findElement(By.xpath("//input[@name='male']"));

gender.click();

System.out.println(gender.isSelected());

WebDriver is the name of the key interface against which tests should be written, but there are several implementations. These
include:
HtmlUnit Driver
This is currently the fastest and most lightweight implementation of WebDriver. As the name suggests, this is based on
HtmlUnit. HtmlUnit is a java based implementation of a WebBrowser without a GUI. For any language binding (other than java)
the Selenium Server is required to use this driver.

Firefox Driver
Controls the Firefox browser using a Firefox plugin. The Firefox Profile that is used is stripped down from what is installed on
the machine to only include the Selenium WebDriver.xpi (plugin). A few settings are also changed by default (see the source to
see which ones) Firefox Driver is capable of being run and is tested on Windows, Mac, Linux. Currently on versions 3.6, 10,
latest 1, latest

Internet Explorer Driver


This driver is controlled by a .dll and is thus only available on Windows OS. Each Selenium release has its core functionality
tested against versions 6, 7 and 8 on XP, and 9 on Windows7.

Open a browser (Ex: Internet Explorer)


driver = Selenium::WebDriver.for :ie
Go to a specified URL
driver.navigate.to 'http://www.orbitz.com/'
driver.get 'http://www.orbitz.com/'
Close the browser
driver.close
Access an Element
Type somethign in the Text box or text area
driver.find_element(:id,'airOrigin').send_keys("MAA")
To Clear the text from text field
driver.find_element(:id,'airOrigin').send_keys [:control, 'a'], :space
Button
driver.find_element(:id,'BUTTON_ID'').click
Drop down list
select_box=driver.find_element(:id,'airStartTime')
options=select_box.find_elements(:tag_name=>"option")
options.each do |option_field|
if option_field.text == '12a-9a'
option_field.click
break
end
end
Check box
driver.find_element(:id,'airNonStopsPreferred').click
Radio button
driver.find_element(:id,'htlChoice').click
To verify Flights radio button selected or not
driver.find_element(:id,'airChoice').selected?
#if it returns TRUE then radio button already selected.

Return the title of the document


puts driver.title
Return true if the specified text appears on the TAG
puts driver.find_element(:class,'welcomeText').text.include?("Welcome to Orbitz")
To Click SPAN Elements
options=driver.find_elements(:tag_name=>"span")
options.each do |span_field|
if span_field.text == 'Find Flights'
span_field.click
break
end
end
Learn selenium webdriver by example
1. Download Eclipse http://www.eclipse.org/downloads/
2. make new java project http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2FgettingStarted%2Fqs-
3.htm
3. Create new class file with main
4. copy paste following code and enjoy
public class ScrapNaukri {

public static void main(String[] args) throws IOException {

WebDriver driver = new FirefoxDriver();


driver.get("http://www.naukri.com");

driver.findElement(By.xpath("//*[@id='spanid_farea']/input[@id='farea']")).sendKeys("QA & Testing");

//Enter Location
//driver.findElement(By.xpath("//*[@id='ql']")).sendKeys("pune");

// Click on Search
driver.findElement(By.xpath("//*[@id='search']")).click();

//Xpaths
String Start_xpath_searchString = "//*[@id='";
String End_xpath_searchString = "']";

FileWriter fstream = new FileWriter("C:\\outfilename.txt", true);


BufferedWriter out = new BufferedWriter(fstream);

try {
while ((driver.findElement(By.xpath("//*[@id='pageNext']"))) != null) {

//Click on each link of search result


for(int i=1;i<=50;i++){

try{
driver.findElement(By.xpath(Start_xpath_searchString + i +End_xpath_searchString )).click();

// Go to Job Details
Set<String> windowids = driver.getWindowHandles();
Iterator<String> iter= windowids.iterator();

String mainWindowId=iter.next();
iter.next();
String tabbedWindowId=iter.next();

driver.switchTo().window(tabbedWindowId);

try{
driver.findElement(By.xpath("//*[@id='viewBtn']/a")).click();
Thread.sleep(1000);

System.out.println(driver.findElement(By.xpath("//*[@id='contactDet']")).getText());
String test = driver.findElement(By.xpath("//*[@id='contactDet']")).getText();
out.write(test);
out.newLine();

}catch(Exception e){
System.out.println("Skipped-----------------------------" + i);
}

driver.close();
driver.switchTo().window(mainWindowId);
}catch (Exception e) {
System.out.println("No more Page links to click");
}

driver.findElement(By.xpath("//*[@id='pageNext']")).click();
}
} catch (Exception e) {
System.out.println("No more Next button");
out.close();
}

Selenium Webdriver Basics


Some basic Selenium WebDriver stuff:

1. Click a RadioButton:
var radioButton = driver.FindElements(By.Name("colorname"))[0];
radioButton.Click();

2. Get a RadioButton value:

var radioButtons = driver.FindElements(By.Name("colorname"));


foreach (var radioButton in radioButtons)
{
if (radioButton.Selected)
Console.WriteLine(radioButton.GetAttribute("value"));
}

3. Check Checkbox:
var checkBox = driver.FindElement(By.Id("checkboxId"));
checkBox.Click();

4. Select from dropdown list:


var select = driver.FindElement(By.Id("elementId"));
var option = select.FindElemets(By.TagName("optionTagName"))[0];
option.Click();

5. Get text row from table:


var table = driver.FindElement(By.TagName("table"));
var row = table.FindElements(By.TagName("td"))[0];
Console.WriteLine(row.Text);

6. Get element using XPath:


var element = driver.FindElement(By.XPath("//*[@id="gbqfq"]"));

7. Implicit waiting:
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

8. Explicit waiting:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
var element = wait.Until(d=>
{
return driver.FindElements(By.ClassName("class"))[0];
});
element.Click();
installing selenium..

In order to start automation with selenium we need the following softwares:

1. IDE

2. Selenium Jars

3. A language to interact with browser.

IDE: It is a tool that enables the programmer to write coding and organizing the code in a simplified manner.

Here in this case will we use eclipse as our IDE.


Downloading eclipse IDE:

Note: One should install Java 1.4 or higher versions before installing Eclipse IDE.

1. Go to GOOGLE
2. Type "download eclipse"
3. The following screen will appear:

4. Click on the first link i.e. "Eclipse Downloads"


5. Then the following screen will be displayed:
6. Click on the "Eclipse IDE for Java EE Developers, 228 MB" based on your system configuration either 32 bit or 64bit.

7. After downloading the Software go to the folder where download has done and click on the icon "eclipse.exe"

8. Then following screen will be displayed.


9. Workspace is the place you want to store your programmes. So give your preferred location to store the programmes and
click on OK. After that the following screen will be displayed.

10. Click on File File-->New-->Project following screen will be displayed:


11. Select JAVA Project click on "Next" then Enter the name of the Project you want as shown in the below screen:

12. Then click on "Finish" and click on the area marked in "red" shown below screen:
13. Finally following screen will be displayed as below later for which we need add selenium jars:
14. This completes the installation of Eclipse IDE

Downloading and Configuring Selenium Jars:

Once the IDE has been configured successfully: Do the following steps to configure selenium selenium in your eclipse IDE:

1. Navigate to the URL "http://docs.seleniumhq.org/download/"

2. Navigate to the bottom of the page and click on "download" corresponding to "Java" as we are dealing with Selenium +
Java + Eclipse:

3. Once the download has completed then extract the Jars of the downloaded Zip file.

4. Now go to the Eclipse IDE

5. Right click on the Project you have created.

6. Navigate to "BuildPath---> Configure Buildpath" then following screen will be displayed: then click on "Libraries"
7. Click on "Add External Jars" then the following screen will be displayed
8. Navigate to the folder where u have downloaded the jars and select all the jars and click on "Open" then following screen
will be displayed:
9. Above step will add all the necessary jar files to our Project, then click on "OK".

10. Now expand our project then following screen will be displayed:
11. This step completes the configuration of Selenium and now we are ready to start writing a automation.

First Program In selenium:

Login in to Gmail account:

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

public class GmialLogin {

public static void main(String[] args) throws Exception


{

WebDriver wd= new FirefoxDriver(); /* Creates firefox Instance*/


wd.get("https://www.gmail.com"); /* Open the firefox browser and enter the URL*/
wd.manage().window().maximize();
Thread.sleep(5000);
wd.findElement(By.xpath("//*[@id='Email']")).sendKeys("youremailemail");
wd.findElement(By.xpath("//*[@id='Passwd']")).sendKeys("password");
wd.findElement(By.xpath("//*[@id='signIn']")).click();

OOP's Concepts

Object Oriented Programming language.


1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Abstraction:
Hiding unnecessary data from the user details is called abstraction.
e.g. TV Remote Buttons.

Encapsulation:
Writing operations and methods stored in single class this is called Encapsulation.
e.g. Medical Capsules.

Inheritance:
The new class is existing from old class, i.e. subclass is existing from super class.
e.g. Father and Son relationship.

Polymorphism:
A single function or single operator has different character in different place.
e.g. Person
- Person in home act is husband / Son.
- In Office acts Employee.
- In public Good citizen.

Selenium RC Selenium Web Driver


Server is required to start No server required to start
Core engine is Javascript Interacts natively with browser
based application
Its a simple and small API Complex and a bit large API as
compared to RC
Less Object orinted API Purely Object oriented API
Cannot move mouse with it Can move mouse cursor
Full xpaths have to be No need to append 'xpath=\\'
appended with 'xapth=\\'
syntax
No Listeners Implementation of Listeners is
provided
Cannot test Can test iphone/Android
iphone/Android applications
applications
Cannot test Can test iphone/Android
iphone/Android applications
applications

I have test cases in different xml files like (testngMozilla.xml, testngChrome.xml, testngIE.xml) and I have main testng.xml file
which hold all the suits

I have test cases in different xml files like (testngMozilla.xml, testngChrome.xml, testngIE.xml) and I have main testng.xml file
which hold all the suits

In my application i have 100 Submit buttons with same name,x path and everything same ,now i want to click on 50 th
Submit button? tell me the process....

You can put all those in an array then click on the element you want using array index?

example code :

WebDriver driver = new FirefoxDriver();


driver.get("http://bbc.com");
List<WebElement> allLinks=driver.findElements(By.xpath("blahblah"));
allLnks.get(49).click();

ques:Can someone tell me how the package structure will be in real time? I mean package under the java project and how the
files will be stored..

ANS: you have different packages for xls files, util files, test cases..
keep everything segregated

Even I wanted to know, the most challenging situation you had when
using Selenium and the biggest bug you found. Can any one help with
this.
ANS:Wanted to share few things based on my experience.

one of the challenging situation would be automating a webpage where applet is involved. If the webpage is developed by the
third party vendor than you will not have any methods/code exposed to automate.
Then you will have to go for an alternative to automate it.
This was one of the situation in my project.
Applet can be handled only if you have the core method exposed to you. You should be in touch with the development team
for this.
Applet can not be identified by firepath. And in my case the webpage was developed by the third party vendor and they are not
ready to expose any method related to applets.

Finally after the days of exploration i came Finding a new tool called Sikuli.

Using this tool anything on the screen can be automated. It is a simple tool, like selenium it is only the jars that you need to add
to your project. I used this tool to automate the Applet part on a page.
Sikuli is another vast concept, this tool is mainly used in Mobile automation for android.

How we can use following things with testng.Any help with small example

Grouping of Test Cases


Executing Particular Test Case more than once
Dependency based Tests
Executing Particular Test Case more than once ....> this is called regression testing

Grouping of Test cases is called Test Suite

Dependency based Tests datadependency,functionality dependency.

i have to capture the text in web page and store it in varible, for that i wrote the following.

ANS: rq=wd1.findElement(By.xpath(".//*[@id='columnTypeB']/form/div[1]/div[7]/p[2]")).getText();
System.Out.Println(rq);

Why do we need listeners


ANS:In general, to detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must have an
object that implements the ActionListener interface. The program must register this object as an action listener on the button
(the event source), using the addActionListener method. So for doing all such kind of events where we click on something needs
coordinates values, we need to implement Listener interface then we register our class and our inbuilt methods related to
mouse/keyboard.


Request you to share the questions once you are done with the interview

1. If you are giving interview for Java-Selenium then it is must to brush-up your Core-Java concepts and definitions
such as,
a. What is Encapsulation?
b. Polymorphism.
c. Difference between (interface & inheritance), (Hash Map and Hash set), (Overriding & Overloading) so on....
d. What is Abstract Class.
e. Access modifiers.
f. Difference between throw and throws
g. IS-A and HAS-A concepts
h. Above listed question are must.
i. Apart from this be ready to write some simple Java programs like, pyramid structure, displaying only odd/even
numbers till 100 and so on.
2. With respect to selenium, if you are good with webdriver fundamentals it is very easy to crack the questions.
The most possible questions are as follows.
a. One common question how to take screen shot.
b. Architecture of Selenium
c. Popup and window handling
d. Difference between implicit and explicit waits and how to implement these and in what scenarios.
e. Be ready to explain your framework from current project. They may ask you to write flow diagram.
f. How to handle frames
g. What are cookies and how to handle.
h. Handling Https websites
i. Difference between Quit and Close
j. How to download files
k. How Profiling is done in Firefox
l. Handling Alerts.
m. How to handle different browsers.
3. Also be ready to face some very simple questions at which we may take small pause to answer those like,
a. Latest version of firefox in market and the version on which you are testing
b. Full form of AJAX, DOM and may be what is AJAX
c. As this interview is part of testing, they may ask you some instant questions like, write some five negative test
cases on pen instantly.

I am sure that answers to these questions will definitely help you clear tech interviews to the maximum extent.

All the best..!

Request you to share the questions once you are done with the interview

Set<String> ids = driver.getWindowHandles();


System.out.println("Total window:" + ids.size());
Iterator<String> iter = ids.iterator();
String MainWindowid = iter.next();
String PopupWindowid = iter.next();
System.out.println("Main window id :" + MainWindowid);
System.out.println("Popup Window id :" + PopupWindowid);

Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); or Driver.manage().timeouts().implicitlyWait(1,


TimeUnit.MINUTES);

I want to know how to get column count from an excel sheet using POI jar files.

xls.getColumnCount("sheetname");

I just copied and pasted the following code and it runs and Hovers over the element. Here is the code
System.setProperty("webdriver.chrome.driver","C:\\Users\\Surya\\Desktop\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.practicefusion.com/");
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
WebElement a= driver.findElement(By.xpath("//li[@class='dropdown']/a[@href='/pages/ehr_features.html']"));
Actions li= new Actions(driver);
li.moveToElement(a).build().perform();

Proxy proxy= new Proxy

DesiredCapabilities cap= newDesiredCapabilities();

cap.setCapability(CapabilityType.BROWSER_NAME, "firefox");

cap.setCapability(CapabilityType.PROXY, proxy);
FirefoxDriver driver= newFirefoxDriver(cap);

driver.get("http://www.google.com");

Can anybody tell me how to upload file into "https://www.transferbigfiles.com/"

my scenario is click on file link and in popup window i have to upload specified file.
WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.transferbigfiles.com/");
Thread.sleep(5000L);
driver.findElement(By.xpath("//input[@id='file-input']")).sendKeys("Enter your file path");

I am trying to use QC 11.0 as an execution tool for selenium.


Have anyone here done it ?
I need guidance in this direction

Selenium tests are written in Programming language and QC tests are written in plain english. so selenium tests cannot be
stored in QC. Also, i dont think, if selenium scripts can be executed from QC.
However you can have your selenium scripts mapped with your QC tests and store the selenium scripts pass/fail result in QC
using the QcTools4j API.
For executing the scripts you can rely on Ant which can trigger your scripts.

I am automation one application with Selenium. This is my first Automation project. So I have some doubts kindly replay....
My client is also modify the application so, testing is doing by them also.

Can we select a exact position in google map using selenium webdriver?

For example i want to select a goa in google map. how can we do this...
can you have a look at this please.

http://code.google.com/p/sikuli-api/wiki/SikuliWebDriver

1) You need to create a NEW package INSIDE a src name it xslt ( donot change the name)

2) Inside xslt package you need to paste testng-results.xls which i have attached here.

3) run ant clean, ant compile, ant run, ant makexsltreports

4) refresh your project.. you will see the Xslt folder been generated and within that folder you will have your outputs.
1. My client is asking 'test scripts' What I have to deliver to them. I think I can deliver class files only, so client can execute by
ANT.

2.What would be the deliverable we give them.

3. Ideal hardware and software requirements to establish this test environment

4. Identify the tasks client needs to perform after each build.

5. Recommend set up that they should follow, i.e run this every time after the application is built. Can this be integrated with
the build process

1.) I think you have some Tool like SVN or GIT in which all Scripts are stored, it is like Central server where the Project
Workspace is, So you do not deliver any type test scripts to the client . just Check-In the Code after you have done your work
on that project and it's reflect automatically on central server when client open the workspace .he automatically see what you
have done so far today

2.) Deliverables are your Daily Routine Task your Seniors(Test Lead) allocated to you

3.) This should be finalize by Sr. Test Team members

4.) This should be identified by Sr. Test Team members




driver.switchTo().window(PopupWindowid);

Hi All,
1. you have 100 applications in ur module so you have to put all the data in a excel sheet... now the question is...... will
you write the data for each application (like login page) in one excel sheet per each application or for all 1000 applications you
write it in a single excel sheet...

2. you have 1000 set of data that u are passing through excel sheet..... now the question is how can u execute 800 test
data in excel sheet and how will you omit 200 test data in excel sheet.

3. you have 2 different test cases and you have to execute 2 methods of ur first test case and 3 methods of ur second
test case in one execution of ur testng.xml file how will you do that.

ANS:. u can do it using data driven via data providers by puting all ur login details in one excel sheet .

2.this is similar to the above one and u can omit the remaining test data by providing keyword like runmode ON / OFF

3. u can use include and exculde methods in ur custum made XML file.
Set<String> winIds = driver.getWindowHandles();

//System.out.println("Total browsers--> " + winIds.size());

java.util.Iterator<String> it = winIds.iterator();

//System.out.println(it.next());

driver.findElement(By.xpath("//*[@id='lnkCountryLookupAIR_CC']")).click();

winIds = driver.getWindowHandles();

//System.out.println("Total browsers--> " + winIds.size());

it = winIds.iterator();

String mainWindowId = it.next();

String tabWindowId = it.next();

//System.out.println(mainWindowId);

// System.out.println(tabWindowId);

driver.switchTo().window(tabWindowId);

driver.findElement(By.xpath("//*[@id='table_itemList']/tbody/tr[243]/td[2]/a")).click();

Ques:In Many interviews the interviewers are stressing on this question can any1 give me some better answer.

1.How to execute one test case (say around 50) 50 times by passing multiple sets of different test-data (may be for example to
test login functionality)

ANS:in case your using Testng use DataProvider to pass multiple sets.
I have used the following code to click on the OK button in javascript prompt box

QUES:WebDriver driver= new FirefoxDriver();


//code
Alert alert = driver.switchTo().alert();
alert.accept();

I got the following error ,please see below:


Exception in thread "main" org.openqa.selenium.NoAlertPresentException: No alert is present (WARNING: The server did not
provide any stacktrace information)

Ans:Try putting Implicit wait


WebDriver driver= new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

QUES:Can any one give me code for this please

Three windows are open. Now I want to active second window and display second window name.

Ans: You can get all winddows id first by

set<String>WinID = driver.getWindowHandles();
Iterator itr = WindID.Iterator();
firstWinID = itr.next();
secondWinID = itr.next();
thirdWinID = itr.next();
String MyTitle = driver.switchTo().Window(secondWinID).getTitle()

Website -> http://www.hdfc.com/others/homeline.asp Right side I want to click on Call Us

driver.findElement(By.xpath("//a[text()=' Call Us']")).click();

QUES:Can someone please help me with how can we handle pop-ups in selenium webdriver

Qns:Selenium normally recognizes popup as the separate window. So the pop up can be handled by extracting the window
handles for particular pop up and switching the focus to the window using the window handles extracted.

Tip:Driver.switchto().defaultcontent()

Hi All,
I have two date fields to select from using the calendar.( Depart date field and Return date field.) The code below only selects
dates for the Depart field only.
Please how do i add the logic to this code to help me select dates from the Return date field????

package com.aainternational.hybrid.testcases;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class BookTest {

static WebDriver driver;

@Test (dataProvider="getData")
public void bookReturn(String depart, String arrive, String d,String adultpax,String childpax) throws InterruptedException,
ParseException{

//String d = "12/05/2013"; // dd/mm/yyyy

String months[] = {"January", "February", "March", "April", "May", "June", "July","August",


"September","October","November","December"};

driver = new FirefoxDriver();


driver.get("http://aa.com/intl/fr/index_en.jsp");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.findElement(By.xpath("//input[@id='origin_display']")).sendKeys(depart);

driver.findElement(By.xpath("//div[@id='resultDiv_0']")).click();
driver.findElement(By.xpath("//input[@id='destination_display']")).sendKeys(arrive);
driver.findElement(By.xpath("//div[@id='resultDiv_0']")).click();

// extract month and date


SimpleDateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
Date myDate = df.parse(d);

Calendar cal = Calendar.getInstance();


cal.setTime(myDate);

int day = cal.get(Calendar.DAY_OF_MONTH);


int month=cal.get(Calendar.MONTH);
int year=cal.get(Calendar.YEAR);
System.out.println(day);
System.out.println(month);
System.out.println(months[month]);
System.out.println(year);

String travelMonth = months[month]+" "+year;


driver.findElement(By.xpath("//*[@id='bookingModule']/div[2]/label[2]/button")).click();

selectMonth(travelMonth);
selectDay(day);

//selecting options from adult drop list


WebElement adultdroplist = driver.findElement(By.xpath("//*[@id='flightSearchForm.adultPassengerCount']"));
adultdroplist.sendKeys(adultpax);

//selecting options from child drop list


WebElement childdroplist = driver.findElement(By.xpath("//*[@id='flightSearchForm.childPassengerCount']"));
childdroplist.sendKeys(childpax);

driver.findElement(By.xpath("//*[@id='bookingModule-submit']")).click();

//select the month from calendar


public static void selectMonth(String monthtobeSelected){
String forwardArrow = "//*[@id='ui-datepicker-div']/div[2]/div/a/span";
String XpathMonthYearSection="//*[@id='ui-datepicker-div']/div[1]/div/div";
while (!driver.findElement(By.xpath(XpathMonthYearSection)).getText().equals(monthtobeSelected)){
driver.findElement(By.xpath(forwardArrow)).click();
}

//select day from calendar- after month is selected


public static void selectDay(int dayToBeSelected){
//*[@id='ui-datepicker-div']/div[1]/table/tbody/tr[3]/td[7]/a

String part1="//*[@id='ui-datepicker-div']/div[1]/table/tbody/tr[";
String part2="]/td[";
String part3="]";

for(int rNum=1; rNum<=5; rNum++){


for(int cNum=1;cNum<=7;cNum++){
String date = driver.findElement(By.xpath(part1+rNum+part2+cNum+part3)).getText();
System.out.print(date+" ");
if(!date.equals(" ")){
int currentDay = Integer.parseInt(date);
if (currentDay == dayToBeSelected){
driver.findElement(By.xpath(part1+rNum+part2+cNum+part3)).click();
return;
}
}
}
System.out.println();
}
}

@DataProvider
public Object [][] getData(){

Object data[][] = new Object [1][5];

//1st row
data [0][0] = "LHR";
data [0][1] = "BOS";
data [0][2] = "24/5/2013";
data [0][3] = "1 Adult (12+";
data [0][4] = "0 Children (2-11)";

/* //2nd row
data [1][0] = "DFW";
data [1][1] = "MIA";
data [1][2] = "30/5/2013";
data [1][3] = "2 Adult (12+";
data [1][4] = "1 Children (2-11)";

*/

return data;

ANS:are you booking a return flight?

if you are booking a return flight, I can not see the data or the logic for it!
you will need the return date and to repeat the logic that populate the departure date for the return date.

if you are booking one way, add the following line to your logic before sending the "depart" string and after implicit wait.
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.findElement(By.xpath("
//*[@id='triptypeColumn']/ul/li[2]/label")).click();

hi
if you want a return flight skip clicking the one way button as in my prev email and after the code lines
driver.findElement(By.xpath("//*[@id='bookingModule']/div[2]/label[2]/button")).click();

selectMonth(travelMonth);
selectDay(day);

add the following:


driver.findElement(By.xpath("//*[@id='bookingModule']/div[3]/label[2]/button")).click();

selectMonth(travelMonth);
selectDay(day);

this will populate the departure date 24/05/2013 into the arrival date as well.
if you want a different date, you need to expand your data to add the desired date to your data and change the logic to read
and populate it the same as above.

Ques:
I am unable to select from dropdown list., in Goair.in. i am trying to select from the "From" drop-down list box. My script
makes the mouse to move to the required location but its not clicking it.
Cld anyone help me to find what tthe poblem is pls. The print statement does print all the list items from the "From" drop-down
box
WebDriver driver =new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get("http://www.goair.in");
/*driver.findElement(By.xpath("//*[@id='cmbOriginHome']")).click();
Thread.sleep(3000L);
WebElement dropdown=driver.findElement(By.xpath("//*[@id='cmbOriginHome']"));
List<WebElement> travel_loc=dropdown.findElements(By.tagName("option"));

System.out.println(travel_loc.size());
for(int i=1;i<travel_loc.size();i++)
{
String get_loc=travel_loc.get(i).getText();
System.out.println(get_loc);
if(travel_loc.get(i).getText().equals(location))
travel_loc.get(i).click();
}*/

ANS: u have to select particular city lets say lucknow and that should be in double quotes.
if(travel_loc.get(i).getText().equlas("lucknow")
Hope this helps

Ques: Can anyone please explain me the steps involved from development to release in agile methodology in terms of manual
and automation QA in detail, thanks in advance.

ANS:Agile methodology is a software development process. Most of the people are using agile these days. Agile is a process
with less documentation, more work and more communication.

Scrum in one of the processes used in agile methodology


For Example:
Scrum can be:
1. 2-3 weeks of sprints where development and QA of the features will be done.
2. We have pre-planning, poker planning meeting to estimate out features(known as user stories in scrum)
3.We have everyday stand up to explain what we did yesterday, what are we doing today and have any blocks in terms of our
work.
I would like to discuss which i know about scrum. In scrum we have sprints. Each sprint period is for 2-3 weeks.

Product Owner is the one who wants us to build the product (can say as customer or product sme) with whom we(including
development team and testers) will have calls.

Scrum Master: To be a scrum master he need to certification but in every company we don't find actual scrum master.
Here our manager acts as scrum master and assigns the roles in the project. He need to participate in daily stand up meetings.

Team Member: All the members of the development team and testing team are called team members.
Ques:

I have a problem,

every time my id element value is getting changed

example:

xpath:
//*[@id="ctl00_ctl25_g_669e9a2c_9c06_418f_8691_f172262a5de6_ctl01_txtUserName"]

next time it is changing to :

xpath:

//*[@id="ctl00_ctl26_g_669e9a2c_9c06_418f_8691_f172262a5de6_ctl01_txtUserName"]

5 is changing to 6.
kindly help me....
ANS:For dynamic contents in XPATh you can use either of the following:-

contains
starts-with
ends-with

IN your case, txtUserName is not changing. So your XPATH would be


//* [contains(@id,'txtUserName')]

WebElementdropelement=driver.findElement(By.xpath("//*[@id='alertEmailTable']/tbody/tr[2]/td[3]/div/ul/li[1]"));

System.out.println(dropelement);
Select s = new Select(dropelement);
s.selectByVisibleText("Delete");

//dropBox xpath
/* WebElement drop=driver.findElement(By.xpath("//*[@id='userIDWrapper']/div"));
List<WebElement> links = drop.findElements(By.xpath("//*[@class='ulSelectBox']"));
System.out.println(links.size());
for(int i = 0; i < links.size(); i++){
System.out.println(links.get(i).getText()); */

Ques:Can any one explain,Difference between ImplicitWait and explicitWait with exapmle? And at what situation we use ?

ANS:Implicit wait will finds the element every time until it present once the element is found it will execute and the explicit wait
will stop the script until the element is found.we use most implicit wait most of the times. If we navigate from one page to
other page and finding an element in that page in such cases we use implicit wait.
To give you a short answer to your questions. Implicit wait is generally used a global wait which waits for any element in your
entire application but I personally did not feel effective using inplicit wait.

Explicit wait is only for a specific element to appear in DOM. And this is powerful than implicit wait.

Ques:I have developed an approach for framework in my company ..( TestNg / Hybrid/ Java ) and now have been asked to
generate an approach to read the data from the XML-results file and convert it to a readable report (xml parsing) and then send
it to the colleagues via mail.

ANS:Use sax or dom parser in java. Each is used to read xls files
Just search on google about them.. u will get lot of info

Tip:I have successfully built the Data driven framework and have run it with ant . Also, I've through the maven modules and
I've learnt how to use maven on a sample project. However, I don't know how to integrate maven into my current data driven
project. My goal is to have the same folder/package structure as I currently have in my data driven framework with the maven
(POM.xml) integrated. Can any one let me know how should I go about this?.. any help from you guys will be greatly helpful ...
!!!!

Please check with the below code.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Css_Header_Navigation {


public static void main (String[] args) throws InterruptedException{
FirefoxDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get("http://www.bhf.org.uk/");
Boolean flag=false;
//System.out.println(driver.findElement(By.xpath("//*[@id='global-nav']/div[1]/div[2]/div[1]/ul/li[1]/span/a")).isDisplayed());
String xpath_root=".//*[@id='global-nav']/div[1]/div[1]/h5";
String xpath_sub="//*[@id='global-nav']/div[1]/div[2]/div[1]/ul/li[1]/span/a";

WebElement root = driver.findElement(By.xpath(xpath_root));


root.click();
Actions builder = new Actions(driver);
builder.moveToElement(root).build().perform();
Thread.sleep(4000L);
WebElement sub = driver.findElement(By.xpath(xpath_sub));
sub.click();
String text= driver.findElement(By.xpath("//*[@id='content']/div[4]/div[1]/h1")).getText();
if (text.equalsIgnoreCase("How your heart works"))
{
flag=true;
System.out.println(flag);
System.out.println(text);
}
}
}

Tip:I have seen both videos "TestNg with Data Driven" and "TestNg with hybrid" frame work. Could any one please let me know
two things:

1. In test "TestNg with Data Driven" framework we are using TestNg Selenium code syntax like @Test, @BeforeTest... etc and
run with the suite.xml
2. In Hybrid we are running with java main function and nothing is related with TestNg code syntax. Its completely written in
the core java...

a. So is it means "TestNg with Data Driven" and "TestNg with hybrid" frame work will be use one at a time ?
b. Are we dont require the suite.xml in hybrid?
c. is we dont require @test, @beforetest .. type syntax of the testNg in the hybrid?

ANS:in Hybrid test framework, you don't need TestNG or Junit. It's just a java application.

Ques:
1.when u execute ur testng.xml file.., how do u find only the failed test cases...? (answer is by looking at testng-failed.xml
file) now the question is what u do when u get ur testcaes failed and how u reexecute ur failed test cases again? what steps u
follow to make ur test case pass? and how u report these failed test cases?

HI Jashu,
now the question is what u do when u get ur testcaes failed and how u reexecute ur failed test cases again?
Ans: For example -1) your 'Add product' test cases is failing. Open your application and check manually add product test case is
working on not? If test case manually failed then it is application issue. Open defect/bug and assign it to developer.
2) If application is working fine then execute your failed test cases again and check where exactly your test case is failing ?
then check your selenium script, xpath, database sheet try to figure out why your test cases is failing ?

Basically there could be 2 scenario in such cases. A Bug or a false positive. If its a bug , report else need to correct automation
code accordingly.

Ques:,

In todays interview one ajax automation question asked please provide the answer.

There are 2 boxes. first box is having a list and second box is empty text box. when user selects an option from the list
then 2nd text box should display the same option text selected in first one and user has to verify that second one is having
correct text.

I was asked to write the code for this. Please share your answers.
Ans:
driver.findelement(by.xpath("dropdown").sendKeys("option"));
String s = driver.findelement(by.xpath("dropdown").gettext());
Boolean test = false;
//looking for text for 25 seconds & even the text is not populated then we explicitly make test fail.
//used explicit wait..(more useful in this type of scenario's)
for(int i = 0;i <25;i++) {
String s1 = driver.findelement(By.xpath("Textbox").getText());
if(s1.equals(s)) {
test = true;
break;
} else {
Thread.sleep(1000L); //1 sec sleep.
}
}
if(test)
sop("Testcase Fail);

its a collection API :Set, Map, List

2. Actions
Actions action = new Actions(driver);
action.click(driver.findElement(By.id("txtUserNotes")));
action.perform();
driver.findElement(By.xpath("//*[@id='txtUserNotes']")).sendKeys("Testing");
driver.findElement(By.xpath("//*[@id='btnSave']")).click();

Below code perform following steps:


1. login into facebook
2. search for sachin
3. verify whether searched text(in this case "sachin") is in search result or not

public static void main(String[] args) {


WebDriver driver1 = new FirefoxDriver();
driver1.get("https://www.facebook.com");
driver1.findElement(By.id("
email")).sendKeys("username");
driver1.findElement(By.id("pass")).sendKeys("password");
driver1.findElement(By.id("u_0_b")).click();

driver1.findElement(By.xpath("//*[@id='q']")).sendKeys("sachin");
String x="sachin";
driver1.findElement(By.xpath("//*[@id='u_0_3']/span/button")).click();
List<WebElement> alllinks = driver1.findElements(By.tagName("a"));
System.out.println(alllinks.size());
for(int i=0 ; i<alllinks.size() ; i++){

if(x.equals(alllinks.get(i).getText())){
System.out.println("record found");
break;

}
use the concept of flag variable (ie) initialise flag to false before the loop and if the rocord is found then assign true to it.
Outside the loop check for flag is false. May be the solution will work

We execute selenium regression script with the help of Jenkins. We hv scheduled the script so at particular time script
automatically get executed.

When you execute your scripts for the first time, the request goes to the server and fetches the data to executes the scripts.
Fetching data from the server takes some time delay. After fetching data the server saves some data on to the client/user
agent, this data is called cookies.
So when you execute the same scripts for the second time, the request doesn't hit the server every time, instead it fetches the
required data from the browsers cache if available and executes the scripts so its takes less time.

Ques:please Can any one let me know how to Print list of all frame names in a webpage using Selenium Webdriver java code?.

Ans:public class iframeTest {

public static void main(String[] args) throws InterruptedException {

ProfilesIni allProfiles = new ProfilesIni();

FirefoxProfile myProfile = allProfiles.getProfile("MyTestProfile");

myProfile.setPreference("capability.policy.default.Window.frameElement.get","allAccess");

WebDriver myTestDriver = new FirefoxDriver(myProfile);

myTestDriver.manage().window().maximize();

myTestDriver.get("http://tinyurl.com/cb3lbho");

Thread.sleep(5000L);

try {

List<WebElement> AlliFrameID = myTestDriver.findElements(By.tagName("iframe"));

System.out.println(AlliFrameID.size());

for(int i=0;i<=AlliFrameID.size();i++){

System.out.println(AlliFrameID.get(i).getAttribute("id")); // c how many iframes are there on the page... ask


ur dev the id for which iframe u r working on... and switch to tha iframe as below..
myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[2]/input")).click(); // perform ur
function on the frame as clicking or writing in txt boxes etc....

} catch (Exception e) {

TDD means test driven development - like using junit/tesng

BDD is behavior driven development - like cucmber/jbehave etc

i come across with following interview question.Any one with answers please reply....

1. how to distinguish 5 checkbox with same xpath/id?


2. syntax of driving values from xml ?

3. components of framework?
4. if there is a text on the page, that text have 7 characters .. first 3 numerals, rest 4 alphabets, how will we make sure that this
pattern is followed?
5. how to simulate the 'tab' key in the keyboard?
6. how to make a readonly variable in java?

I have made an attempt to answer few of the questions which are as follows

1. if 5 checkbox have same xpath/id, then those check boxes can be distinguished based on the attributes
(.getAttribute("attributeName")). any one of the attribute will be unique in all 5 checkbox. Attributes can be name, value,
tabindex. If they are tabing the web elements in a sequence then the 'tabindex' should be unique in all 5 checkbox.

2. Not sure

3. General Frame work components: Properties files, configuration files, Data sheets, Keywords repository, Testbase class,
Utilities Class, Test cases, Reports, Logs

4. First Use getText() and try to parse (Integer.parseInt(string_var) the first 3 characters if successful in try catch block then it is
a integer. For alphabets use isAplhabet() built in function to asses each of 4 alphabets

5. Usually we do not simulate the tab key, instead we refer each element by its tabindex. Tabindex attribute will be unique for
every web element which is associates with tabkey.

6. its by declaring a variable as final.

2. Use SaxParser (which is inbuilt in Java) to parse any xml file and read.

Hi,
I have been asked to extract the price for first and the last item of the search results

1) Invoke "www.amazon.co.uk"

2) Search - Ipad

3) Retrieve the price value of the first and the last item

To reterive the first items price, I am using

String FirstItemPrice = driver.findElement(By.xpath("//*[@id1='result_0']/ul[1]/li[1]/a/span")).getText();

System.out.println("Price is --->"+FirstItemPrice);

I am getting error --> org.openqa.selenium.NoSuchElementException:

Complete code is as below

WebDriver driver = new FirefoxDriver();

driver.get("http://www.amazon.co.uk");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//Enter Ipad in the search window and Search for it

driver.findElement(By.xpath("//*[@id='twotabsearchtextbox']")).sendKeys("Ipad");

driver.findElement(By.xpath("//*[@id='nav-bar-inner']/div/form/div[2]/input")).click();

//Verify if the search is successful

String SearchResults = driver.findElement(By.xpath("//*[@id='resultCount']/span")).getText();

String Temp[] = SearchResults.split(" ");

String str = Temp[5];

String str2[] = str.split(",");

String FinalNumString = str2[0]+str2[1];


int numOfRes = Integer.parseInt(FinalNumString);

System.out.println("the Stringnumber is -->"+numOfRes);

if (numOfRes > 0){

Assert.assertEquals(Temp[6], "Results");

System.out.println("Number of Results Displayed is --> "+numOfRes);

System.out.println("Is REsults Displayed--> "+Temp[6]);

//Get the price of first item

String FirstItemPrice = driver.findElement(By.xpath("//*[@id1='result_0']/ul[1]/li[1]/a/span")).getText(); -> Element not found

System.out.println("Price is --->"+FirstItemPrice);

String TempPrice[] = FirstItemPrice.split("");

int PriceOfFirstItem = Integer.parseInt(TempPrice[0]);

System.out.println("price of the first item --->"+PriceOfFirstItem);

Thanks

How to switch control to pop-up window ?

If you want to do any operations in pop-up window you need to switch the control to pop-up window then do all your
operations in that and finally close the pop-up window and again select the default (main ) window.

here is WebDriver logic to select Pop-up window

1 . Pop-up window has name/id

driver.switchTo().window("<window name>");

2. Pop-up window doesn't have name / you don't want to hard code the window name then go for below logic.

Method-1

before opening pop-up get the main window handle.

String mainWindowHandle=driver.getWindowHandle();
open the pop-up (click on element which causes open a new window)

webElement.click();

try to get all available open window handles with below command. (the below command returns all window handles
as Set)

Set s = driver.getWindowHandles();

from that above set try get newly opened window and switch the control to that (pop-up window handle), as we
already know the mainWindowHandle.

Set s = driver.getWindowHandles();
Iterator ite = s.iterator();
while(ite.hasNext())
{
String popupHandle=ite.next().toString();
if(!popupHandle.contains(mainWindowHandle))
{
driver.switchTo().window(popupHandle);
}
}

Now control is in pop-up window, do all your operations in pop-up and close the pop-up window.
Select the default window again.

driver.switchTo().window( mainWindowHandle );

Method-2

// get all the window handles before the popup window appears
Set beforePopup = driver.getWindowHandles();

// click the link which creates the popup window


driver.findElement(by).click();

// get all the window handles after the popup window appears
Set afterPopup = driver.getWindowHandles();

// remove all the handles from before the popup window appears
afterPopup.removeAll(beforePopup);

// there should be only one window handle left


if(afterPopup.size() == 1) {
driver.switchTo().window((String)afterPopup.toArray()[0]);
}

How to Identify popup window in Selenium Webdriver ?


1. First Check whether its popup window or IFrame window by using IE Developer or Find bug tools.

2. If its popup window then use following code :


driver.findElement(By.xpath("")).click();

Set s=driver.getWindowHandles();

This method will help to handle of opened windows other than parent

Iterator ite=s.iterator();

while(ite.hasNext())

String popupHandle=ite.next().toString();

if(!popupHandle.contains(mwh))

driver.switchTo().window(popupHandle);

/**/here you can perform operation in pop-up window**

//After finished your operation in pop-up just select the main window again

driver.switchTo().window(mwh);

This method will help to filter out of all opened windows

1) String parentWindowHandle = browser.getWindowHandle(); // save the current window handle.

WebDriver popup = null;

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

If its IFrame then use following line.

String parentWindowHandle = driver.getWindowHandle();

driver.switchTo().Frame(driver.findelement(by.id("iframeid")));
// perform ur actions.
//revert back to parent control
driver.switchTo().window(parentWindowHandle);

Drop down Select - WebDriver

In web application we see many drop down lists for many input fields (Ex : gender, age, country..etc). This drop down option is
different from normal text/numeric input field. It has separate tag <select></select>in html.

In automation while filling most of the forms we need to fill/select the drop down values also. For achieving this WebDriver has
separate class called Select.

In this post we will see what are all different method available in Select class.

Consider below example

HTML CODE
<select id="city">
<option value="Op1">Chennai</option>
<option value="Op2">Hyderabad</option>
<option value="Op3">Bangalore</option>
</select>

Select an Option
Available methods for selecting an option are

1. selectByIndex(int index)
2. selectByValue(java.lang.String value)
3. selectByVisibleText(java.lang.String text)

selectByIndex(int index)
Select the option at the given index.
Usage :
new Select(driver.findElement(By.id("city"))).selectByIndex(2);
In above example it will select the Hyderabad because it is in index 2.

selectByValue(java.lang.String value)
Select all options that have a value matching the argument.
Usage :
new Select(driver.findElement(By.id("city"))).selectByValue("Op3");
In above example it will select the Bangalore based on the value attribute of that option.

selectByVisibleText(java.lang.String text)
Select all options that display text matching the argument.
Usage :
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Chennai");
In above example it will select the Chennai based on the visible text.

De-select an option
Available methods for de-selecting an option(s) are,

1. deselectAll()
2. deselectByIndex(int index)
3. deselectByValue(java.lang.String value)
4. deselectByVisibleText(java.lang.String text)
deselectAll()

Clear all selected entries.

deselectByIndex(int index)

Deselect the option at the given index.

deselectByValue(java.lang.String value)

Deselect all options that have a value matching the argument.

deselectByVisibleText(java.lang.String text)

Deselect all options that display text matching the argument.

Getting all options


Some times we may in need to get all the options available in drop down list in that case below method will be useful.

getOptions();

getOptions()
It will return All options belonging to this select tag
Usage :
List<WebElement> allCities=new Select(driver.findElement(By.id("city"))).getOptions();
for(WebElement city:allCities)
{
System.out.println(city.getText()); //It will return the text of each option
System.out.println(city.getAttribute("value")); //it will return the value attribute of each option
}

Get Selected Option(s)


If you want to verify whether the proper value got selected in particular drop down list you can make use of below methods.

1. getFirstSelectedOption();
2. getAllSelectedOptions() ;

getFirstSelectedOption();

The first selected option in this select tag (or the currently selected option in a normal select)

getAllSelectedOptions() ;

It will return List of All selected options belonging to this select tag. (This will be useful for multiselect picklist)

Handling multi-select pick list

HTML CODE
<select id="city" multiple>
<option value="Op1">Chennai</option>
<option value="Op2">Hyderabad</option>
<option value="Op3">Bangalore</option>
</select>

Handling multi select pick list same as normal drop down( single pick list).
For selecting both Hyderabad, Bangalore option you need to use one of the below logics.

new Select(driver.findElement(By.id("city"))).selectByIndex(2);
new Select(driver.findElement(By.id("city"))).selectByIndex(3);
Or
new Select(driver.findElement(By.id("city"))).selectByvalue("Op2");
new Select(driver.findElement(By.id("city"))).selectByvalue("Op3");
Or
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Hyderabad");
new Select(driver.findElement(By.id("city"))).selectByVisiableText("Bangalore");

I hope you understand WebDriver Select class usage in automation.

How to get auto populated Google search result?

Using below logic you can get the auto populated search result (Google search) for your search word

Logic
driver.get("http://www.google.co.in");
driver.findElement(By.name("q")).sendKeys("Test");
List<WebElement> autoPopulatedList=driver.findElements(By.cssSelector("tr>td>span"));
for(WebElement ele:autoPopulatedList)
{
System.out.println(e.getText());
}

Example
Output of given code for above search word is
selenium rc sendkeys
selenium puthon by
selenium
selenium tutorial
selenium ide
selenium webdriver
selenium rc
selenium ide download
selenium grid
selenium documentation

MouseOver method in WebDriver

Use below method for mouseover action in WebDriver

public void mouseOver(WebDriver driver,WebElement element) throws Exception


{
new Actions(driver).moveToElement(element).perform();
}

Working with frames/iframes in Selenium/WebDriver

In a very simple word, Frames or IFrames can be treated as web page inside a web page. And no wonder, Selenium also treats
them in same line. That means, you have to switch to a frame, to find elements present inside that frame. And you need to
come out of the frame when you want to find elements outside of the frame.

1st thing to remember is frame/Iframes are nothing but Web Elements in side a web page. So you can use findElement()
method to find out the frame/Iframe. But there is another simple way, where you only provide the name of the frame and
Selenium and Web Driver automatically switch the control to that frame.

Consider the below HTML portion, where two frames are present. To find out an element inside those frames, you need to
switch the control to that frame.
######################################################
<frame name="Frame1" id="Frame1">
-----------
-----------
-----------
</frame>

<frame name="Frame2" id="Fram2">


----------
-----------
-----------
</frame>
######################################################

Lets find out frame1 using find element technique:


WebElement frame = driver.findElement(By.Name("Frame1"));
or
WebElement frame = driver.findElement(By.Id("Frame1"));

Now you can use frame object to switch the control.


driver.switchto.frame(frame);

In the method above, you need get the object web element and then use it in switchto method.

But you can directly call the switchto method on frame name like:
driver.switchto.frame("Frame1");

You can also switch to frame by using index of the frame.


In the above example, to switch to "Frame1" using index, the code will be like :
driver.switchto.frame(0);

And the last thing is once you switch to a frame, then you must go out of the frame to find elements outside of the frame
boundry.
driver.switchto.defaultcontent();

How to get List Elements and Select a Value from a DropDown List - Selenium WebDriver

How to Select a value from a DropDown List using Selenium - WebDriver

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.Select;
public class MySpiceJet {

public static void main(String[] args) throws Exception


{
WebDriver wd=new FirefoxDriver();
wd.get("http://www.spicejet.com/");
Thread.sleep(10000);

WebElement from1=wd.findElement(By.id("from1Select"));
// Get the list from the drop down list Selenium WebDriver
List<WebElement> list1=from1.findElements(By.tagName("option"));
for(WebElement i:list1)
{
System.out.println(i.getText());
//Reporter.log(i.getText());
}
// Select a value from the drop down list Selenium WebDriver
Select select=new Select(wd.findElement(By.id("from1Select")));
select.selectByVisibleText("Tirupati");

wd.close();
}

I imported all those things like below:

import java.awt.List;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import com.thoughtworks.selenium.Selenium;

public class we122


{
public static WebDriver driver = new FirefoxDriver();
public static Selenium selenium;
@Test
public void testUntitled() throws Exception {
String valToBeSelected;
driver.get("" + "file:///C:/Documents%20and%20Settings/Madhuri/Desktop/a.html");
new Select(driver.findElement(By.name("AllVal")) ).selectByVisibleText("A");
driver.findElement(By.name("mt")).sendKeys("mmmmmm");
Thread.sleep(11111);
System.out.print("finished");
driver.close();
List<WebElement> options = driver.findElements(By.tagName("option"));
for (WebElement option : options)
{
if (valToBeSelected.equalsIgnoreCase(option.getText())){
option.click(); }
}

}
}

Here is the sample code which will start typing "vam" and then capture all search suggestions .
view plainprint?

1. import java.util.Iterator;
2. import java.util.List;
3. import java.util.concurrent.TimeUnit;
4. import org.openqa.selenium.By;
5. import org.openqa.selenium.WebDriver;
6. import org.openqa.selenium.WebElement;
7. import org.openqa.selenium.firefox.FirefoxDriver;
8. import org.testng.annotations.BeforeTest;
9. import org.testng.annotations.Test;
10.
11. public class SearchSuggestion {
12.
13. WebDriver driver;
14.
15. @BeforeTest
16. public void start(){
17. driver = new FirefoxDriver();
18. }
19.
20. @Test
21. public void SearchSuggestion() {
22.
23. driver.get("http://google.com");
24. driver.findElement(By.id("gbqfq")).sendKeys("vam");
25. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
26.
27. WebElement table = driver.findElement(By.className("gssb_m"));
28. List<webelement> rows = table.findElements(By.tagName("tr"));
29. Iterator<webelement> i = rows.iterator();
30. System.out.println("-----------------------------------------");
31. while(i.hasNext()) {
32. WebElement row = i.next();
33. List<webelement> columns = row.findElements(By.tagName("td"));
34. Iterator<webelement> j = columns.iterator();
35. while(j.hasNext()) {
36. WebElement column = j.next();
37. System.out.println(column.getText());
38. }
39. System.out.println("");
40.
41. System.out.println("-----------------------------------------");
42. }
43. }
44. }</webelement></webelement></webelement></webelement>

Permission denied for to get property Window.frameElement Command duration or timeout: 12 milliseconds

I used to get the below error when I try to switch to iframe ( driver.switchTo().frame("iframe_canvas") ).

Permission denied for <https://apps.facebook.com> to get property Window.frameElement Command duration or timeout: 12
milliseconds Build info: version: '2.21.0', revision: '16552', time: '2012-04-11 19:09:00' System info: os.name: 'Windows 7',
os.arch: 'amd64', os.version: '6.1', java.version: '1.6.0_23' Driver info: driver.version: RemoteWebDriver
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)

Seems this issue is happening because of Cross Origin .


Solution to this problem is set the below settings in Firefox Profile.

I changed my code as below. Now it is working fine :)


view plainprint?

1. import org.openqa.selenium.By;
2. import org.openqa.selenium.WebDriver;
3. import org.openqa.selenium.WebElement;
4. import org.openqa.selenium.firefox.FirefoxDriver;
5. import org.openqa.selenium.firefox.FirefoxProfile;
6. import org.testng.annotations.BeforeTest;
7. import org.testng.annotations.Test;
8.
9. public void IframeTest(){
10.
11. WebDriver driver;
12.
13. @BeforeTest
14. public void setUpDriver() {
15. FirefoxProfile profile = new FirefoxProfile();
16. profile.setPreference("capability.policy.default.Window.QueryInterface", "allAccess");
17. profile.setPreference("capability.policy.default.Window.frameElement.get","allAccess");
18. driver = new FirefoxDriver(profile);
19. }
20.
21. @Test
22. public void delete(){
23. Common.FBLogin(fbUsername, fbPassword, driver);
24. driver.get("appURL");
25. driver.switchTo().defaultContent();
26. driver.switchTo().frame("iframe_canvas");
27. }
28.
29. }
Selecting a date from Datepicker using Selenium WebDriver

Calendars look pretty and of course they are fancy too.So now a days most of the websites are using advanced jQuery
Datepickers instead of displaying individual dropdowns for month,day,year. :P

If we look at the Datepicker, it is just a like a table with set of rows and columns.To select a date ,we just have to navigate to the
cell where our desired date is present.

Here is a sample code on how to pick a 13th date from the next month.

view plainprint?

1. import java.util.List;
2. import java.util.concurrent.TimeUnit;
3. import org.openqa.selenium.By;
4. import org.openqa.selenium.WebDriver;
5. import org.openqa.selenium.WebElement;
6. import org.openqa.selenium.firefox.FirefoxDriver;
7. import org.testng.annotations.BeforeTest;
8. import org.testng.annotations.Test;
9.
10. public class DatePicker {
11.
12. WebDriver driver;
13.
14. @BeforeTest
15. public void start(){
16. System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
17. driver = new FirefoxDriver();
18. }
19.
20. @Test
21. public void Test(){
22.
23. driver.get("http://jqueryui.com/datepicker/");
24. driver.switchTo().frame(0);
25. driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
26. //Click on textbox so that datepicker will come
27. driver.findElement(By.id("datepicker")).click();
28.
29. //Click on next so that we will be in next month
30. driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();
31.
32. /*DatePicker is a table.So navigate to each cell
33. * If a particular cell matches value 13 then select it
34. */
35. WebElement dateWidget = driver.findElement(By.id("ui-datepicker-div"));
36. List<webelement> rows=dateWidget.findElements(By.tagName("tr"));
37. List<webelement> columns=dateWidget.findElements(By.tagName("td"));
38.
39. for (WebElement cell: columns){
40. //Select 13th Date
41. if (cell.getText().equals("13")){
42. cell.findElement(By.linkText("13")).click();
43. break;
44. }
45. }
46. }
47. }</webelement></webelement>

org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed.

The solution to the above problem is to specify the location of firefox in your script .
view plainprint?

1. System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");

Here is my modified script.And it went through without any errors :)

view plainprint?

1. import org.openqa.selenium.By;
2. import org.openqa.selenium.WebDriver;
3. import org.openqa.selenium.firefox.FirefoxDriver;
4. import org.testng.annotations.BeforeTest;
5. import org.testng.annotations.Test;
6.
7. public class FacebookRegistration {
8.
9. WebDriver driver;
10.
11. @BeforeTest
12. public void start(){
13. System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
14. driver = new FirefoxDriver();
15. }
16.
17.
18. @Test
19. public void run(){
20. driver.get("http://facebook.com");
21. }
22. }

WebDriver Tutorial Part 6 : Working with the different types of web elements

From the previous post , it was clear on how to identify the webelements on webpage. In this post we will see how to work with
different webelemts.

By default , selenium defines predefined functions which we can use on different types of webelemts.
Here are some of the predefinied functions:

driver.findElement(By.id("WebelemntId")).clear();
driver.findElement(By.id("WebelemntId")).isEnabled();
driver.findElement(By.id("WebelemntId")).isDisplayed();
driver.findElement(By.id("WebelemntId")).submit();
driver.findElement(By.id("WebelemntId")).sendKeys("test");
driver.findElement(By.id("WebelemntId")).isSelected();
driver.findElement(By.id("WebelemntId")).getAttribute("");
driver.findElement(By.id("WebelemntId")).getLocation();
driver.findElement(By.id("WebelemntId")).getTagName();
driver.findElement(By.id("WebelemntId")).getText();
driver.findElement(By.id("WebelemntId")).getSize();

All the functions canot be used for every webelement.

Say "sendKeys()" method is sending text to a webelement .This method can be used with textboxes but we can't use it on
images , links. These are all basic things which we will learn through experience.

Here are the samples , on how to achieve basic functionality of different webelements using webdriver functions:

Textboxes :Send text


Sending text to Textboxes can be done by using "sendKeys()" method. Here is how it works:

view plainprint?

1. driver.findElement(By.id("textBoxId")).sendKeys("sending text");

RadioButtons :Select an option


Selecting an option from Radio button can be done by using "click()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("radioButtonId")).click();

Hyperlinks :Click on links


Clicking on link can be done by using "click()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("linkId")).click();
Checkboxes :Check the checkboxes
Selecting options from Checkboxes can be done by using "click()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("checkBoxId")).click();

Drop-down List :Select an option


Selecting an option from Dropdown list can be done by using "sendKeys()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("dropdownListId")).sendKeys("SelectOption1");

Textarea :Send text


Sending text to Textboxes can be done by using "sendKeys()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("textAreaId")).click();

Button :click on it.


Submitting button can be done by using either "click()" or "submit()" mrthods.Here is how it works:
view plainprint?

1. driver.findElement(By.id("butonId")).click();

Below example is the working code for "submitting a form which has most of the webelements like textbox, textarea,
radiobutton, checkboxe and dropdown list".
view plainprint?

1. package blog;
2.
3. import org.openqa.selenium.By;
4. import org.openqa.selenium.WebDriver;
5. import org.openqa.selenium.firefox.FirefoxDriver;
6. import org.testng.annotations.AfterTest;
7. import org.testng.annotations.BeforeTest;
8. import org.testng.annotations.Test;
9.
10. public class DocumentIdentifiers {
11.
12. WebDriver driver;
13.
14. @BeforeTest
15. public void start(){
16. driver = new FirefoxDriver();
17. }
18.
19. @Test
20. public void ok(){
21. driver.get("https://docs.google.com/spreadsheet/viewform?fromEmail=true&formkey=dGp5WEhMR0c1SzFTRFhmTj
JNVk12T1E6MQ");
22. //Send text to firstname, lastname and email address fields
23. driver.findElement(By.id("entry_0")).sendKeys("First Name");
24. driver.findElement(By.id("entry_3")).sendKeys("Last Name");
25. driver.findElement(By.id("entry_13")).sendKeys("Emailaddress");
26. //Setting value for Gender radiobutton
27. driver.findElement(By.id("group_2_1")).click();
28. //Selecting values for "Your preferred Programming language" checkbox
29. driver.findElement(By.id("group_5_1")).click();
30. driver.findElement(By.id("group_5_2")).click();
31. driver.findElement(By.id("group_5_3")).click();
32. //Setting value for "your Location" dropdown list
33. driver.findElement(By.id("entry_6")).sendKeys("Non India");
34. //Giving the value for user rating radiobutton
35. driver.findElement(By.id("group_7_3")).click();
36. //sending value to feedback textarea elemenet
37. driver.findElement(By.id("entry_8")).sendKeys("Adding new comments ");
38. //Submitting the form
39. driver.findElement(By.name("submit")).submit();
40. }
41.
42. @AfterTest
43. public void close(){
44. driver.quit();
45. }
46. }

WebDriver Tutorial Part 5 : Locating WebElemnts on the Webpage

Every webpage is nothing but the set of of different elments. So we need to have idea on the following things before we start
building the script.
1.Knowing the different elements on WebPage
2.Locating the elements on web page
3.Working wth the elemets

1. Knowing the different typesof elements on WebPage


By looking at the webpage we should be able to identify the type of element it consists.Sometimes we can check elements
types by viewing the source code.Here are the common elements most of the time we encounter in the process of automation.
Text box
Drop-down List
Checkbox
Radio button
TextArea
Hyperlink
Image
Button
Frames
Alert dialog box
Window

2.Locating the elements on web page


Before starting let us have a look at the below sample form which consists of "First Name, Last name , Email address, Sex,
Submit button".

First name:

Last name:
Email Address:

Your Sex :

Male

Female

Above form has 5 elements, three textboxes, one radio button and one submit button.We have successfully identified the
elements type.Now we need to locate the elements on webpage using Selenium.

If we see the viewsource of "First Name" textbox , it will look like


<input id="firstname" maxlength="45" name="firstname" type="text" />

It means we can locate the "First Name" text box on the webpage using 4 different locators i.e id, name, Xpath, CSS.
view plainprint?

1. WebDriver driver=new FirefoxDriver()


2. WebElement textbox=driver.findElement(By.name("firstname"));
3. OR
4. WebElement textbox=driver.findElement(By.id("firstname"));

We can easily get the Xpath and CSS values of an element using firefox addons like Firebug and FirePath.

In selenium we can identify the elements on the webpage with the following locators.
Locating By Id
Locating By Name
Locating By Xpath
Locating Hyperlinks by LinkText
Locating By DOM
Locating By CSS

3.Working wth the elemets


Knowing the element type and locating the element is not what we actually want. We want to work with those elements to
perform some action on the webpage say "locate the submit button on webpage and click on it".

WebDriver Tutorial Part 6 : Working with the different types of web elements

From the previous post , it was clear on how to identify the webelements on webpage. In this post we will see how to work with
different webelemts.

By default , selenium defines predefined functions which we can use on different types of webelemts.
Here are some of the predefinied functions:

driver.findElement(By.id("WebelemntId")).clear();
driver.findElement(By.id("WebelemntId")).isEnabled();
driver.findElement(By.id("WebelemntId")).isDisplayed();
driver.findElement(By.id("WebelemntId")).submit();
driver.findElement(By.id("WebelemntId")).sendKeys("test");
driver.findElement(By.id("WebelemntId")).isSelected();
driver.findElement(By.id("WebelemntId")).getAttribute("");
driver.findElement(By.id("WebelemntId")).getLocation();
driver.findElement(By.id("WebelemntId")).getTagName();
driver.findElement(By.id("WebelemntId")).getText();
driver.findElement(By.id("WebelemntId")).getSize();

All the functions canot be used for every webelement.

Say "sendKeys()" method is sending text to a webelement .This method can be used with textboxes but we can't use it on
images , links. These are all basic things which we will learn through experience.

Here are the samples , on how to achieve basic functionality of different webelements using webdriver functions:

Textboxes :Send text


Sending text to Textboxes can be done by using "sendKeys()" method. Here is how it works:

view plainprint?

1. driver.findElement(By.id("textBoxId")).sendKeys("sending text");

RadioButtons :Select an option


Selecting an option from Radio button can be done by using "click()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("radioButtonId")).click();

Hyperlinks :Click on links


Clicking on link can be done by using "click()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("linkId")).click();

Checkboxes :Check the checkboxes


Selecting options from Checkboxes can be done by using "click()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("checkBoxId")).click();

Drop-down List :Select an option


Selecting an option from Dropdown list can be done by using "sendKeys()" method.Here is how it works:
view plainprint?

1. driver.findElement(By.id("dropdownListId")).sendKeys("SelectOption1");

Textarea :Send text


Sending text to Textboxes can be done by using "sendKeys()" method.Here is how it works:
view plainprint?
1. driver.findElement(By.id("textAreaId")).click();

Button :click on it.


Submitting button can be done by using either "click()" or "submit()" mrthods.Here is how it works:
view plainprint?

1. driver.findElement(By.id("butonId")).click();

Below example is the working code for "submitting a form which has most of the webelements like textbox, textarea,
radiobutton, checkboxe and dropdown list".
view plainprint?

1. package blog;
2.
3. import org.openqa.selenium.By;
4. import org.openqa.selenium.WebDriver;
5. import org.openqa.selenium.firefox.FirefoxDriver;
6. import org.testng.annotations.AfterTest;
7. import org.testng.annotations.BeforeTest;
8. import org.testng.annotations.Test;
9.
10. public class DocumentIdentifiers {
11.
12. WebDriver driver;
13.
14. @BeforeTest
15. public void start(){
16. driver = new FirefoxDriver();
17. }
18.
19. @Test
20. public void ok(){
21. driver.get("https://docs.google.com/spreadsheet/viewform?fromEmail=true&formkey=dGp5WEhMR0c1SzFTRFhmTj
JNVk12T1E6MQ");
22. //Send text to firstname, lastname and email address fields
23. driver.findElement(By.id("entry_0")).sendKeys("First Name");
24. driver.findElement(By.id("entry_3")).sendKeys("Last Name");
25. driver.findElement(By.id("entry_13")).sendKeys("Emailaddress");
26. //Setting value for Gender radiobutton
27. driver.findElement(By.id("group_2_1")).click();
28. //Selecting values for "Your preferred Programming language" checkbox
29. driver.findElement(By.id("group_5_1")).click();
30. driver.findElement(By.id("group_5_2")).click();
31. driver.findElement(By.id("group_5_3")).click();
32. //Setting value for "your Location" dropdown list
33. driver.findElement(By.id("entry_6")).sendKeys("Non India");
34. //Giving the value for user rating radiobutton
35. driver.findElement(By.id("group_7_3")).click();
36. //sending value to feedback textarea elemenet
37. driver.findElement(By.id("entry_8")).sendKeys("Adding new comments ");
38. //Submitting the form
39. driver.findElement(By.name("submit")).submit();
40. }
41.
42. @AfterTest
43. public void close(){
44. driver.quit();
45. }
46. }

Connecting to DataBase using WebDriver

Our scripts are not just clicking on links we will do more.Yes , of course more :) and one of that "more" is "checking DB".
But Web Driver cannot directly connect to Database. You can only interact with your Browser using Web Driver.SO if you want
to connect to Database then you need to write piece of code which will let you to connect to Database to perform further
actions(insertion, deletion, updation).

For this we use JDBC("Java Database Connectivity").The JDBC API is a Java API for accessing virtually any kind of tabular
data.The value of the JDBC API is that an application can access virtually any data source and run on any platform with a Java
Virtual Machine.

In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do three things:

1.Establish a connection with a data source


2.Send queries and update statements to the data source
3.Process the results

1.Establish a connection with a data source


The traditional way to establish a connection with a database is to call the method
DriverManager.getConnection(URL, "myLogin", "myPassword" )
URL : jdbc:<subprotocol>:<subname>
<subprotocol>-the name of the driver or the name of a database connectivity mechanism
<subname> - The point of a subname is to give enough information to locate the data source .(Includes IP address , Port
number and exact name of DataSource)

For connecting to MYSQL URL will be


jdbc:mysql:<<subname>>

2.Send queries and update statements to the data source


A Statement object is used to send SQL statements to a database over the created connection in Step 1.
Statement-created by the Connection.createStatement methods. A Statement object is used for sending SQL statements with
no parameters.
PreparedStatement-created by the Connection.prepareStatement methods. A PreparedStatement object is used for
precompiled SQL statements. These can take one or more parameters as input arguments (IN parameters).
CallableStatement-created by the Connection.prepareCall methods. CallableStatement objects are used to execute SQL stored
procedures
In Short
createStatement methods-for a simple SQL statement (no parameters)
prepareStatement methods-for an SQL statement that is executed frequently
prepareCall methods-for a call to a stored procedure

3.Process the results


A ResultSet is a Java object that contains the results of executing an SQL query.We will have separate post on it.The JDBC API
provides three interfaces for sending SQL statements to the database

Here is the code for it.

//Load the mysql driver dynamically


Class.forName("com.mysql.jdbc.Driver");
//Establish connection
Connection con = DriverManager.getConnection("jdbc:mysql:wombat", "myLogin", "myPassword");
//Create statement Object
Statement stmt = con.createStatement();
//Execute the query and store the results in the ResultSet object
ResultSet rs = stmt.executeQuery("SELECT id, name, salary FROM employee");
//Printing the column values of ResultSet
while (rs.next()) {
int x = rs.getInt("id");
String s = rs.getString("name");
float f = rs.getFloat("salary");
}

I have a selenium RC code below which selects list of drop down values and stores in array

String [] abc = selenium.getSelectOptions("c");


for(int i=1; i<abc.length; i++)
log.info(i+" : "+abc[i]);

how to do the same with webdriver

would suggest to you use List instead of String to store the values. You could use WebDriver to achieve this as following -

// List to hold drop down values


List<String>dropDownValues = new ArrayList<String>();

// List to hold drop down elements in drop down


List<WebElement> dropDownElement = new Select(driver.findElement(By
.cssSelector("drop down locator"))).getAllSelectedOptions();

// Store drop down values


for(WebElement element: dropDownElement) {
dropDownValues.add(element.getText());
}

// Print drop down values


for(String value: dropDownValues) {
System.out.println(value);
}

Let us know if you have any doubt.

How to retrieve web table content using Selenium WebDriver

There are many ways we can do this,


but in below example i am following "tr","td" approach.

WebDriver driver=new FirefoxDriver();


driver.manage().window().maximize();
driver.get("http://money.rediff.com/");

WebElement element=driver.findElement(By.id("allpage_links"));
List<WebElement> rowCollection=element.findElements(By.xpath("//*[@id='allpage_links']/tbody/tr"));

System.out.println("Numer of rows in this table: "+rowCollection.size());


//Here i_RowNum and i_ColNum, i am using to indicate Row and Column numbers. It may or may not be required in real-time
Test Cases.
int i_RowNum=1;
for(WebElement rowElement:rowCollection)
{
List<WebElement> colCollection=rowElement.findElements(By.xpath("td"));
int i_ColNum=1;
for(WebElement colElement:colCollection)
{
System.out.println("Row "+i_RowNum+" Column "+i_ColNum+" Data "+colElement.getText());
i_ColNum=i_ColNum+1;
}
i_RowNum=i_RowNum+1;
}
driver.close();

How to retrieve a specifec cell value from a web table using Selenium WebDriver

Here in this example i covering how to retrieve a specific cell value from Web Table using Selenium WebDriver:

The below code works well if the Cell contains plain text than any other controls etc.

int rownum,colnum;
String s_xpath;
WebDriver driver=new FirefoxDriver();
driver.get("https://www.irctc.co.in/");

rownum=2;
colnum=1;
//Here i am framing the xpath with rownum and colnum
s_xpath="//*[@id='tabslinks']/tbody/tr["+rownum+"]/td["+colnum+"]";

//getText method retrieves the cell value.


System.out.println(driver.findElement(By.xpath(s_xpath)).getText());

Let us list some of the actions that we need to automate while automating a test case:

1. Click a link, button


2. Type value in an Edit box
3. Select a value from the dropdown
4. Check / Uncheck a checkbox
5. Select a radio button

This is exactly what I am going to discuss in this post.

Click a link / button:

To click on an object through webdriver first we need to find out which locator we are going to use. Is it ID, name, xpath, or
css? For this purpose we can utilize firebug / xpath checker to find out is there any id / name exists for the object we are going
to perform action upon. Then write the code as below:

driver.findElement(By.xpath("//a[@href='CustomerInfo.htm']")).click();

In the above line of code driver could be FirefoxDriver, InternetExplorerDriver, ChromeDriver, HtmlUnitDriver, etc. On one of
these browsers we are going to find an element and then click as per the code.

findElement is an API provided by the webdriver which requires argument By.xpath. The xpath can be replaced by one of
the below methods if we need to identify the element with any other attributes such as css, name, classname, etc:

1. className
2. cssSelector
3. linkText
4. name
5. partialLinkText
6. tagName
7. xpath
8. id

To understand the above methods one needs the basic understanding of the HTML. Id, name, input, type, a, etc are the HTML
tags / attributes. Using these HTML tags and attributes xpath can be constructed and this I have already explained in one of
my earlier posts (How to write xpath)

Type value in an Editbox


Have a look at the below line of code.

driver.findElement(By.name("FirstName")).sendKeys("Google");

Here the webdriver finds the object first with findElement API and then keys in the value with sendKeys method.

Select a value from the dropdown

To select a value from a dropdown, follow the below steps:

1. Declare a List and assign all the values of dropdown using findElements method
2. Use a for loop to go through the elements one by one
3. Using an IF condition match the required option
4. Click the required option (.setSelected is deprecated)

Use the below code and put that into a function which does the job.

public static void selectValue(String valToBeSelected){


List <WebElement> options = driver.findElements(By.tagName("option"));
for (WebElement option : options) {
if (valToBeSelected.equalsIgnoreCase(option.getText())){
option.click();
}
}
}

call the static method wherever necessary selectValue(Texas) will select the value Texas from the dropdown country.

Check / Uncheck a checkbox

To Check / Uncheck a checkbox, the object needs to be identified using findElement method and then just click. To find out
whether the checkbox is checked or not utilize the method element.isSelected()

WebElement kancheck = driver.findElement(By.name("kannada"));


kancheck.click();
System.out.println(kancheck.isSelected());

Above code snippet will first click the checkbox named kannada and then verifies whether it is clicked or not.

Select a radio button

Follow the same steps which are used in Checkbox to select a radio button and then verify the status using isSelected() method.

WebElement gender = driver.findElement(By.xpath("//input[@name='male']"));


gender.click();
System.out.println(gender.isSelected());

Suppose this is the source ::

Afghanistan
Albania
India
China
Here,

Select sel = new Select(driver.findElement(By.name(country)));


sel.selectByValue();
> It selected China, As the value given is empty which matches with the value of China

Select sel = new Select(driver.findElement(By.name(country)));


sel.selectByIndex(3);
> It selected China , As index starts from 0 and China is the 3rd element

Basic String Operations in Java

public class StringOperations {

public static void main(String args[]){


String str1="Hello";
String str2="Ja va";
String str3="Hello";

// String Operations

System.out.println("String1 == String3"+ str1.equals(str3));


System.out.println("String2 at Index 2:"+str2.charAt(2));
System.out.println("Compare Str2 and Str3"+str2.compareTo(str3));
System.out.println("Compare str1 and str3"+str1.compareTo(str3));
System.out.println("String2 contains Ja: "+str2.contains("Ja"));
System.out.println("String is empty ?"+str1.isEmpty());
System.out.println("Sting HashCode"+ str1.hashCode());
System.out.println("Substring of String1"+str1.substring(2, 3));
System.out.println("Remove whitespaces in String2"+str2.trim());
System.out.println("Convert to LowerCase"+str2.toLowerCase());
System.out.println("Replace a with A"+str3.replace('a','A'));
}
}

OutPut:

========

String1 == String3true

String2 at Index 2:

Compare Str2 and Str32

Compare str1 and str30

String2 contains Ja: true

String is empty ?false


Sting HashCode69609650

Substring of String1l

Remove whitespaces in String2Ja va

Convert to LowerCaseja va

Replace a with AHello

Palindrome in Java for Integers and Strings

public class JavaPalindrome {

public static void main(String arg[]){


int num=121;
String str="teet teet";
System.out.println("Given Number"+num+"is Palindrome:"+intPalindrome(num));
System.out.println("Given String"+str+"is Palindrome:"+stringPalindrome(str));
System.out.println("String reverse using toChar Array");
System.out.println("Given String"+str+"is Palindrome:"+stringCharArrayPalindrome(str));
}

private static boolean stringCharArrayPalindrome(String str) {


String rev="";
char arr[]=str.toCharArray();
for(int i=arr.length-1;i>=0;i--)
rev=rev+arr[i];
if(str.equalsIgnoreCase(rev))
return true;
else
return false;

private static boolean stringPalindrome(String st) {


String str1[]=st.split("");
String revstr="";
for(int i=str1.length-1;i>=0;i--){
revstr+=str1[i];
}
if(st.equalsIgnoreCase(revstr))
return true;
else
return false;
}

// Checking Number Palindrome or not


private static boolean intPalindrome(int num) {
int n = num;
int rev = 0;
for (int i = 0; i <= num; i++)
{
int r = num % 10;
num = num / 10;
rev = rev * 10 + r;
i = 0;
}

if (n == rev) {
return true;
} else {
return false;
}
}/** Number palindrome */

Checked vs Unchecked Exceptions


=============================

Checked exceptions should be handled in the code.

Compile error will throw for checked exception if we are not handling in code.

Unchecked exception
===================
NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Checked exception
=============
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException

Polymorphism in Java Using Overloading and Overridden methods

Polymorphism
One form and many implementations.
It can be acheived by using inheritence,overloading and Overriding.
Compile time Polymorphism: Over loading
Runtitme Polymorphism: Over riding
Runtime Polymorphism /Dynamic method dispatch:
Its a process in which a call to an overridden methodis resolved at runtime rather than compile itme.
Dynamic Binding: Refers to linking of a procedure call to the code to be executed in response to the call
Also known as late binding :Code associated to procedure call is not known untile the time of the call at runtime.
Overloading.
Two or more methods with same name in the same class with different arguments.

Overloaded methods Must change the argument list


May change the return type
May change the access modifiers.
May change the checded exceptions.

Example:
package com.oops;

public class OverLoadingExample {

public int sum(int a,int b){


System.out.println("Int Int");
return a+b;
}

public double sum(double a,double b){


System.out.println("Double Double");
return a+b;
}

public int sum(int a,double b){


System.out.println("Int Double");
return (int) (a+b);
}
public static void main(String args[]){

OverLoadingExample oe=new OverLoadingExample();


System.out.println("Overloading method"+oe.sum(3, 7));
System.out.println("Overloading method"+oe.sum(2.5, 5.7));
System.out.println("Overloading method"+oe.sum(2, 5.5));
}
}

Output:
=======
Int Int
Overloading method10
Double Double
Overloading method8.2
Int Double
Overloading method7

Overriding:

Occurs in the subclass and declares method that has same type arguments as a method and declared by one of its super class.
It can be used for defining the behaviour of child class.
Argument list same as overriden method.
Constructors canot be overridden.
final methods canot be overridden.
Static method cannot be overridden but can be re-declared.
super() can be used for invoking parent class(Super class) methods.

Example
package com.oops;

class OverExample{

public void fun1(){


System.out.println("Super Function1");
}

public void fun2(){


System.out.println("Super Using super() Function2");
}

}
public class OverRiddingExample extends OverExample{

public void fun1(){


System.out.println("Subclass Function1");
}

public void fun2(){


super.fun2();
System.out.println("Subclass Function2");
}

public static void main(String[] args) {


OverExample or=new OverRiddingExample();
OverExample oe=new OverExample();
or.fun1();
oe.fun1();
or.fun2();
}

Output:
========

Subclass Function1
Super Function1
Super Using super() Function2
Subclass Function2
Writing to File Using Java Programming Language

package com.io;

import java.io.*;
import java.util.Scanner;

public class FileWrite {

public static void main(String args[]){

try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name");

//Passing File name to File Class


String file=br.readLine();
File fname = new File(file);

boolean exist=fname.createNewFile();

//Verifying file exists or not ..


if(!exist){
System.out.println("File already exists");
System.exit(0);
}
else
{
FileWriter fwrite=new FileWriter(file);
BufferedWriter bwr=new BufferedWriter(fwrite);
bwr.write(br.readLine());
bwr.close();

System.out.println("Successfully created");
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

Output:

========

Enter File name


Hello.txt

Hello first file

Successfully created

Reading File in Java Using Java Programming

package com.io;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileRead {

public static void main(String args[]){

try
{
String str;
FileInputStream in=new FileInputStream("C:\\Downloads\\FRead.txt.txt");
DataInputStream din=new DataInputStream(in);
BufferedReader br=new BufferedReader(new InputStreamReader(in));

while((str=br.readLine())!= null){
System.out.println(str);
}
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}

}
}

Output:

==========

Hi,

This is first file for reading

Thanks

Collection Java Programming Interview Questions 1


Collection API ?
Java Collections framework API is a unified architecture for representing and manipulating collections. All collections
frameworks contains interface, implementations and algorithms. Following are the benefits of collection framework.
Reduces programming efforts. - Increases program speed and quality.
Allows interoperability among unrelated APIs.
Reduces effort to learn and to use new APIs.
Reduces effort to design new APIs.
Encourages & Fosters software reuse.
Collection contains six interfaces.
Set, List and SortedSet: extends collection interface
Map and SortedMap : dont extend collection interface.a

What is HashMap and Map?


Maps stores key Value pair, and Hashmap is class that implements that using hashing technique.

Diff HashTable Vs HashMap Vs HashSet

Hashtable
Hashtable is basically a datastructure to retain values of key-value pair. Doesnot allow null for key and values
It is synchronized. So it comes with its cost. Only one thread can access in one time
Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on
a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

Hashtable<Integer,String> rank= new Hashtable<Integer,String>();

rank.put(1,"A");
rank.put(1,"B");
rank.put(1,"C");

rank.put(null,"E"); NullPointerException at runtime

System.out.println(rank.get(1));
System.out.println(rank.get(2));

HashMap
Like Hashtable it also accepts key value pair.Allows null values
It is unsynchronized. So come up with better performance
By using following command Hashmap can be synchronized.
Map m = Collections.synchronizedMap(hashMap);

HashMap<Integer,String> Lang= new HashMap<Integer,String>();

Lang.put(1, "java");
Lang.put(2, null);

HashSet
HashSet does not allow duplicate values.
It can be used where you want to maintain a unique list. You also use its contain method to check whether the object is already
available in HashSet.
It provides add method rather put method.

HashSet<String> str= new HashSet<String>();

str.add ("Apple");
str.add ("Boy");
str.add ("Cat");

if (str.contains("Apple"))

Iterator and implementation


An iterator is an object that enables a programmer to traverse a collection.
Iterator iter = list.iterator();
while (iter.hasNext()) {
System.out.print(iter.next());
if (iter.hasNext())
System.out.print(", ");
}

Diff Iterator Vs ListIterator


Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements
ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

Interface Implementation:

Implementations

Interface Array Balanced Tree Linked List Hash table

List ArrayList LinkedList

Map TreeMap HashMap

Set TreeSet HashSet

Deque ArrayDeque LinkedList

Code for finding and printing webelements from the dropdown list:

/* Code for finding and printing webelements from the dropdown list:
WebElement dropdown= Driver.findElementByTagName("Select");
List<WebElement> dropdownelements=dropdown.findElements(By.tagName("option"));
System.out.println(dropdownelements.size());
dropdownelements.get(2).click();
for (i=0;i<=dropdownelements.size();i++)
{
System.out.println(dropdownelements.get(i).getAttribute("Value"));
}*/

8. What is the difference between assert and Verify Commands?

Ans:

There are two mechanisms for validating elements that are available on the application under test. The first is assert: this
allows the test to check if the element is on the page. If it is not available, then the test will stop on the step that failed. The
second is verify: this also allows the test to check whether the element is on the page, but if it isnt, then the test will carry on
executing.

WebDriver with TestNG - Gmail Login Functionality

Below is the code for GMAIL Login functionality using WebDriver with TestNG

package com.test.webdriver;
import static org.testng.AssertJUnit.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Driver {


private WebDriver driver;
@BeforeClass
public void Startup(){
driver = new FirefoxDriver();
}
@Test (description="Google Login")
public void GoogleLogin() throws Exception{
driver.get("http://www.gmail.com");
assertEquals("Sign in", driver.findElement(By.id("signIn")).getAttribute("value"));
driver.findElement(By.id("Email")).sendKeys("*********");
driver.findElement(By.id("Passwd")).sendKeys("**********");
driver.findElement(By.id("signIn")).click();
Thread.sleep(10000);
driver.switchTo().frame("canvas_frame");
driver.findElement(By.id("gbgs4dn")).click();
driver.findElement(By.id("gb_71")).click();
driver.switchTo().defaultContent();
assertEquals("Sign in to Gmail", driver.findElement(By.id("button")).getText());
}
@AfterClass
public void teardown(){
driver.quit();
}
}

Advantages of WebDriver
Advantages of web driver

1) Support for iPhone and Android testing


2) Implementation of listeners - a much awaited feature
3) Better features for Ajax testing.
4) You can easily simulate clicking on front and back button of browser.
5) You can extract objects in bulk like QTP. For ex - extract all links of page. With RC this was a big hastle
6) Unlike RC you dont have to start a server in webdriver.
7) You can simulate movement of a mouse using selenium.
8) Tabs and pops are more or less the same. RC can also handle and Webdriver can also handle.
9) You can find coordinates of any object using Webdriver.
10) You have classes in Webdriver which help you to simulate key press events of keyboard.
10) Keyword driven framework is very easy to build in webdriver.

Tweaking an existing Firefox profile

Suppose that you wanted to modify the user agent string (as above), but you've got a tricked out Firefox profile that contains
dozens of useful extensions. There are two ways to obtain this profile. Assuming that the profile has been created using
Firefox's profile manager ("firefox -ProfileManager"):

ProfilesIni allProfiles = new ProfilesIni();


FirefoxProfile profile = allProfiles.getProfile("WebDriver");
profile.setPreferences("foo.bar", 23);
WebDriver driver = new FirefoxDriver(profile);

Alternatively, if the profile isn't already registered with Firefox:

File profileDir = new File("path/to/top/level/of/profile");


FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.setPreferences(extraPrefs);
WebDriver driver = new FirefoxDriver(profile);

Enabling features that are disabled by default in Firefox

Native events is such a feature: It is disabled by default for Firefox on Linux as it may cause tests which open many windows in
parallel to be unreliable. However, native events work quite well otherwise and are essential for some of the new actions of the
Advanced User Interaction. To enable them:

FirefoxProfile profile = new FirefoxProfile();


profile.setEnableNativeEvents(true);
WebDriver driver = new FirefoxDriver(profile);

How to set language in profile

profile.setPreference( "intl.accept_languages", "no,en-us,en" );


Handle popup windows in Selenium 2

Testing popup windows

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.

Handle popup windows in Selenium 2

Testing popup windows

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.

File scrFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\Local Disk D_9220122129\\tmp.jpg"));

Reusable Script In Selenium

import java.io.FileInputStream;

import jxl.Sheet;
import jxl.Workbook;

import com.thoughtworks.selenium.DefaultSelenium;
public class ReusableScript {
public static DefaultSelenium selenium = new DefaultSelenium("localhost",
6666, "*iehta", "http://");
public static String gmail() throws Exception {
selenium.start();
selenium.open("http://www.gmail.com");
selenium.windowMaximize();
Thread.sleep(2000);
selenium.click("link=Create an account ");
selenium.waitForPageToLoad("30000");
return "pass";
}
public static String Register() throws Exception {
FileInputStream fi = new FileInputStream(
"D:\\Framework\\TestData\\Register.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
for (int i = 1; i < s.getRows(); i++) {
if (!s.getCell(3, i).getContents().equals("")) {
if (s.getCell(2, i).getContents().contains("Text")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.type(s.getCell(0, i).getContents(), s.getCell(
3, i).getContents());
}
} else if (s.getCell(2, i).getContents().contains("Combo")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.select(s.getCell(0, i).getContents(), "label="
+ s.getCell(3, i).getContents());
}
} else if (s.getCell(2, i).getContents().contains("chkbox")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.click(s.getCell(0, i).getContents());
}

} else if (s.getCell(2, i).getContents().contains("Radio")) {


if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.click(s.getCell(0, i).getContents());
}

}
else if (s.getCell(2, i).getContents().contains("Button")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.click(s.getCell(0, i).getContents());
}
}
}
}

return "pass";
}

public static void main(String[] args) throws Exception {


// TODO Auto-generated method stub
gmail();
Register();

DriverScript and Execute_testcases

import java.io.FileInputStream;
import java.lang.reflect.Method;

import com.thoughtworks.selenium.DefaultSelenium;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class DriverScript{
static String className = null;
public static String urlpath=null;
public static int rs=1;
public static String result=null;
public static DefaultSelenium selenium=new DefaultSelenium("localhost",6666,"*iehta","http://");
public static boolean Set_Execution_sheet(String strPath) throws Exception
{
String urlpath=strPath;
FileInputStream file= new FileInputStream(urlpath);
Workbook wb=Workbook.getWorkbook(file);
Sheet sh=wb.getSheet(0);
selenium.start();
selenium.open(sh.getCell(1, 1).getContents());
selenium.windowMaximize();
return true;
}
public static boolean Execute(String str) throws Exception
{
FileInputStream file=new FileInputStream(str);
Workbook wb=Workbook.getWorkbook(file);
Sheet s=wb.getSheet(0);
for(int iRownum=1;iRownum<=s.getRows();iRownum++) { String ScreenShotPath="D:\\Framework\\Results\\"+"screenshot"+rs
+".jpg"; try { if(!(s.getCell(5, iRownum).getContents()).contentEquals("")) { className=s.getCell(5, iRownum).getContents(); }
else{ for(int i=iRownum;i>1;i--)
{
if(!(s.getCell(5, i).getContents()).contentEquals(""))
{
className=s.getCell(5, i).getContents();
break;
}
}
}
String functioncall = s.getCell(6, iRownum).getContents();
int inumofparameters=0;
Object ret = null;
String methodName = functioncall.substring(0,functioncall.indexOf("("));
String strparameters = functioncall.substring(functioncall.indexOf("(")+1,functioncall.indexOf(")"));
String strparameterslist[]=strparameters.split(",");
inumofparameters= strparameterslist.length;
selenium.captureScreenshot(ScreenShotPath);
if(strparameters.length()==0){
inumofparameters=0;
}
Class c = Class.forName(className);
if(inumofparameters!=0){
Class cParameters[]=new Class[inumofparameters];
for(int temp=0;temp {
cParameters[temp]= String.class;
}
Method m = c.getMethod(methodName,cParameters );
Object ob = c.newInstance();
Object arglist[] = new Object[inumofparameters];
for(int iparameternum=0;iparameternum {
arglist[iparameternum] = new String(strparameterslist[iparameternum]);
}
ret = m.invoke(ob,arglist);
}else
{
Method m = c.getMethod(methodName,null);
Object ob = c.newInstance();
ret = m.invoke(ob,null);
System.out.println("return value:"+ ret);
}
rs++;
}catch(Exception e){
selenium.captureScreenshot(ScreenShotPath);
e.printStackTrace();
}
}

return true;

}
}

-----------

public class Execute_Testcases Extends DriverScript {


public static void main(String[] args) throws Exception
{
DriverScript.Set_Execution_sheet("D:\\Framework\\Environment\\url.xls");
DriverScript.Execute("D:\\Framework\\MainScript\\testcases.xls");

Export Result to Excel Either login pass of fail

import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.thoughtworks.selenium.DefaultSelenium;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class Export_Login {


public static String status = "pass";
public static String export() throws Exception {
FileInputStream file = new FileInputStream(
"D:\\Framework\\TestData\\login_Data.xls");
Workbook w = Workbook.getWorkbook(file);
Sheet s = w.getSheet(0);
FileOutputStream fo = new FileOutputStream(
"D:\\Framework\\Results\\Loginout.xls");
WritableWorkbook wwb = Workbook.createWorkbook(fo);
WritableSheet ws = wwb.createSheet("login", 0);
String a[][] = new String[s.getRows()][s.getColumns()];
DefaultSelenium selenium = new DefaultSelenium("localhost", 6666,
"*iehta", "http://");
selenium.start();
selenium.open("http://mail.in.com");
selenium.windowMaximize();

for (int i = 0; i < s.getRows(); i++) {


selenium.type("f_id", s.getCell(0, i).getContents());
selenium.type("f_pwd", s.getCell(1, i).getContents());
selenium.click("//input[@value='' and @type='submit']");
Thread.sleep(10000);
if (selenium.isElementPresent("link=Sign out")) {
selenium.click("link=Sign out");
Thread.sleep(6000);
status = "Pass";
System.out.println("if loop" + status);
} else {
status = "Fail";
System.out.println("else loop" + status);
}
for (int j = 0; j < s.getColumns(); j++) {

a[i][j] = s.getCell(j, i).getContents();


Label l = new Label(j, i, a[i][j]);
Label Res = new Label(2, 0, "Result");
Label rs = new Label(2, i, status);
ws.addCell(l);
ws.addCell(Res);
ws.addCell(rs);
System.out.println("The contents are" + a[i][j]);
}
selenium.open("http://mail.in.com");
}
wwb.write();
wwb.close();
return "pass";
}

public static void main(String[] args) throws Exception {


// TODO Auto-generated method stub

export();
}

Export to Excel

import java.io.FileOutputStream;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Export_Excel {
public static String export() throws Exception
{
FileOutputStream fo=new FileOutputStream("D:\\Framework\\Results\\Result_export.xls");
WritableWorkbook wwb=Workbook.createWorkbook(fo);
WritableSheet ws=wwb.createSheet("Res", 0);
Label l=new Label(1,0,"ramesh");
Label l1=new Label(0,0,"reddy");
Label l2=new Label(2,3,"Duplicate");
Label l3=new Label(0,0,"oracle");
ws.addCell(l);
ws.addCell(l1);
ws.addCell(l2);
wwb.write();
wwb.close();

return "pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
export() ;

Login using Excel data

import java.io.FileInputStream;
import jxl.Sheet;
import jxl.Workbook;
import com.thoughtworks.selenium.DefaultSelenium;
public class Excel extends DriverScript{
public static String login_Excel() throws Exception
{
//DefaultSelenium selenium=new DefaultSelenium("localhost",6666,"*iehta","http://");
FileInputStream file=new FileInputStream("D:\\Framework\\TestData\\login_Data.xls");
Workbook w=Workbook.getWorkbook(file);
Sheet s=w.getSheet(0);
FileInputStream fi=new FileInputStream("D:\\Framework\\ObjectRepository\\login_OR.xls");
Workbook w1=Workbook.getWorkbook(fi);
Sheet s1=w1.getSheet(0);
//Sheet s=w.getSheet("Sheet1");
/*selenium.start();
selenium.open("http://mail.in.com");
selenium.windowMaximize();
*/
// for (int i = 1; i < s.getRows(); i++) {

selenium.type(s1.getCell(0, 1).getContents(), s.getCell(0, 1).getContents());


selenium.type(s1.getCell(1, 1).getContents(), s.getCell(1, 1).getContents());
//System.out.println("the value of i"+i);
//}

// selenium.setTimeout("10000");
selenium.click(s1.getCell(2, 1).getContents());

return "pass";
}
public static String close()
{
selenium.close();
return "pass";
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//login_Excel();

Selenium Frameworks

Types of Framework

Any framework is made up of a number of reusable modules & function libraries that are developed with the following
characteristics in mind:

Maintainable
Reusable
Manageable
Accessible
Robust
Flexibility
Measurable

Frame work has several types and most popular are the below :

Frame work has several types and most popular are the below :

a.Keyword driven frame work


b.Data driven driven frame work
c.Hybrid framework

Key word Driven Frame work :

Keyword driven framework is an action based test method used in planing and implementation of automation.

Data Driven Framework :

Data driven is the design of possible inputs what may be given by the end user.
This would cover maximum probabilities of an input data.
It can either be Spread sheet(excel)/sql/CSV.
We have to connect and pass the values to the respective field or element.
The data should be designed by the experienced person on the project. It may be a client or even non technical person but
should be more familiar from an end users prospective.
We have to map the file path properly.

Hybrid Framework:
The Hybrid Automation Framework is otherwise referred to in the industry as a "Hybrid Keyword Data Driven Automation
Framework".

Getting Data from web page

import com.thoughtworks.selenium.DefaultSelenium;

public class GetDataExample {

public static DefaultSelenium selenium=new DefaultSelenium("localhost",6666,"*iehta","http://");


public static String Bodytext()
{
selenium.start();
selenium.open("http://google.com");
selenium.windowMaximize();
selenium.type("q", "abc");
String str=selenium.getBodyText();
//String str=selenium.getHtmlSource();
String link[]=selenium.getAllWindowNames();

System.out.println("The links are"+link.length);


System.out.println("The links are"+link[0]);

selenium.captureScreenshot("D:\\Selenium\\page.jpg");
return "pass";
}
public static String Dynamic()
{
selenium.click("add1");
String windname[]=selenium.getAllWindowNames();
String windid[]=selenium.getAllWindowIds();
String windtitle[]=selenium.getAllWindowTitles();
selenium.getValue("");

System.out.println("The window names are"+windname.length);


selenium.selectWindow(windname[1]);
selenium.click("ok");

return "pass";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Bodytext();
}

TestNg

TestNG Annotation
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.

@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.

@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.

@AfterClass: The annotated method will be run after all the test methods in the current class have been run.

@Parameters: Describes how to pass parameters to a @Test method.


import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;
import com.thoughtworks.selenium.*;

public class googlesearchpage extends SeleneseTestCase{

Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="50000";
private SeleniumServer seleniumServer;

@BeforeClass
@Parameters({"selenium.host","selenium.port","selenium.browser","selenium.url"})
public void setUp(String host, String port, String browser , String url ) throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();

rc.setSingleWindow(true);

seleniumServer = new SeleniumServer(rc);


selenium = new DefaultSelenium(host, Integer.parseInt(port), browser, url);
seleniumServer.start();
selenium.start();

@Test
@Parameters({"search","expected"})
public void googling(String search, String expected) {
selenium.open("/");
selenium.waitForPageToLoad("6000");
selenium.type("q", search);
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent(expected));

}
@AfterTest
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumServer.stop();

TestNG Suite

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">


<suite name="googlesearchpage" verbose="3">
<parameter name="selenium.host" value="localhost"></parameter>
<parameter name="selenium.port" value="4444"></parameter>
<parameter name="selenium.browser" value="*iexplore"></parameter>
<parameter name="selenium.url" value="http://www.google.com"></parameter>

<test name="googlesearchpage">
<parameter name="search" value="seleniumresource.blogspot.com"></parameter>
<parameter name="expected" value="seleniumresource.blogspot.com"></parameter>
<classes>
<class name="googlesearch"></class>
</classes>
</test>
</suite>

Run the test case as TestNG test suite.


Go to googlesearchpage .java page right click on the page the click on Run as... and select the suite in the dialog box which you
created above.

How to pass parameters in selenium RC using TestNG

import org.openqa.selenium.server.RemoteControlConfiguration;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;

import java.io.*;
import java.sql.*;

public class TestExcelEx extends SeleneseTestBase {

@DataProvider(name="DP1")
public Object[][] createData(){
Object[][] retObjArr = {{"testuserA","password1"},
{"testuserB","password2"},
{"testuserC","password3"},
{"testuserD","password4"},
{"testuserE","password5"},
};
return(retObjArr);
}

private SeleniumServer seleniumServer;


Selenium selenium;

@BeforeClass
public void setUp()throws Exception{
RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.trustAllSSLCertificates();
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost",4444,"*iexplore","http://www.google.com");
seleniumServer.start();
selenium.start();
}

@Test (dataProvider = "DP1")


public void testEmployeeData(String username, String password){
selenium.open("https://gmail.com/");
selenium.type("username", username);
selenium.type("passwd",password);
selenium.click(".save");
selenium.waitForPageToLoad("50000");
assertTrue(selenium.isTextPresent("Hi,"+username));
selenium.click("_test_sign_out");
selenium.waitForPageToLoad("50000");

}
@AfterTest
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumServer.stop();

How to pass parameters to JUNIT or TestNG test case.

You can parametrize your test cases using excel sheet. With the help you TestNG we can pass different set of data to our test
cases by following steps

Create a Data file Excel rename Column as username and fill below data like

username
test1
test2
test3
test4

create a DSN through control pannel--> administrative tool--> Data source (ODBC) --> select system DSN --> click add then
select "driver do Microsoft excel" select workbook your data file which you created above.

Now your data source and provider is ready now connect this in your test cases using Java class for
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

import org.openqa.selenium.server.RemoteControlConfiguration;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.*;
import org.testng.annotations.*;

public class TestExcelEx extends SeleneseTestBase {

@BeforeClass
public void setUp()throws Exception{

RemoteControlConfiguration rc = new RemoteControlConfiguration();


rc.trustAllSSLCertificates();
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost",4444,"*firefox","http://www.yahoo.com");
seleniumServer.start();
selenium.start();
}
@Test
public void testread()throws Exception{
// Connection connection = null;

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection( "jdbc:odbc:ex" );
// Connection con = DriverManager.getConnection( "jdbc:odbc:ex" ); here you write your driver which you created using ODBC
connecting excel workbook.

Statement st = con.createStatement();
ResultSet rs = st.executeQuery( "Select * from [Sheet1$]" );

ResultSetMetaData rsmd = rs.getMetaData();


int numberOfColumns = rsmd.getColumnCount();

while (rs.next()) {

for (int i = 1; i <= numberOfColumns; i++) {


if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue);
selenium.open("/");

pause(5000);
selenium.click("link=Sign in");
selenium.waitForPageToLoad("50000");
try {
if (selenium.isElementPresent("//a[@id='overridelink']"))
selenium.click("//a[@id='overridelink']");
}
catch (Exception e) {}
pause(30000);
selenium.type("userid", columnValue);
selenium.type("pass","password");
selenium.click("//button[@class='bfbt' and @type='submit']");
pause(8000);
String wc = selenium.getTable("//div[@id='dynamicmenu-hdrCtr']/table[1].0.1");
System.out.print(wc);

selenium.click("link=Sign out");
selenium.waitForPageToLoad("30000");
selenium.isTextPresent("Welcome!");

}
System.out.println("");

st.close();
con.close();

} catch(Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());

System.out.print(e.printStackTrace());
}
}
}

Runing test script in multiple browsers using WebDriver

we can run test script in different browsers using web driver. Write one test script and configure in testng xml to run that test
case in IE, firefox chrome.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class WebDriverDemo {

private static WebDriver driver = null;

@Test
@Parameters( {"BROWSER"})
public void testread(String BROWSER)throws Exception{

System.out.println("Browser: " + BROWSER);

if (BROWSER.equals("FF")) {
System.out.println("FF is selected");
driver = new FirefoxDriver();
} else if (BROWSER.equals("IE")) {
System.out.println("IE is selected");
driver = new InternetExplorerDriver();
} else if (BROWSER.equals("HU")) {
System.out.println("HU is selected");
driver = new HtmlUnitDriver();
} else if (BROWSER.equals("CH")){
System.out.println("Google chrome is selected");
driver = new ChromeDriver();
}
driver.navigate().to("http://www.yahoo.com");
Thread.sleep(10000);

WebElement search= driver.findElement(By.name("p"));


search.sendKeys("automation blog by niraj");
search.submit();

Thread.sleep(5000);
Assert.assertTrue(driver.getPageSource().contains("automationtricks.blogspot.com"),"Failed in "+ BROWSER);
driver.close();

}
}

In the above sample program BROWSER is a variable which value would be passed from TestNG.xml and TestNG.xml will run
the test multiple time each time BROWSER value would be set with different browser name and test will check the BROWSER
value and decide which browser test will run.

TestNG.xml

<?xml version="1.0" encoding="UTF-8"?>


<suite name="webDriver">
<test name="WebDriverDemo Witn FF" preserve-order="true">
<parameter name="BROWSER" value="FF" />
<classes>
<class name="com.web.WebDriverDemo" />
</classes>
</test>
<test name="WebDriverDemo with IE" preserve-order="ture">
<parameter name="BROWSER" value="IE"></parameter>
<classes>
<class name="com.web.WebDriverDemo"></class>
</classes>
</test>
<test name="WebDriverDemo with HTML unit" preserve-order="true">
<parameter name="BROWSER" value="HU"></parameter>
<classes>
<class name="com.web.WebDriverDemo"></class>
</classes>
</test>
<test name="WebDriverDemo with chrome" preserve-order="true">
<parameter name="BROWSER" value="CH"></parameter>
<classes>
<class name="com.web.WebDriverDemo"></class>
</classes>
</test>
</suite>

Working With Properties file using java

//Reading Properties file

Properties p = new Properties();

try{
p.load(new FileInputStream("propertyname.properties");

}
catch(Exception e ){
e.printStackTrace();
}

//Writing Properties file

Properties p = new Properties();


try{
p.load(new FileOutputStream(("propertyname.properties"),null);
}

catch(Exception e)
{
e.printStackTrace();
}

Selenium 2.0 WebDriver Some useful APIs

To start with WebDriver we need to learn about some of the useful APIs that are provided for automating user actions on an
application.

Let us list some of the actions that we need to automate while automating a test case:

1. Click a link, button


2. Type value in an Edit box
3. Select a value from the dropdown
4. Check / Uncheck a checkbox
5. Select a radio button

This is exactly what I am going to discuss in this post.

Click a link / button:

To click on an object through webdriver first we need to find out which locator we are going to use. Is it ID, name, xpath, or css?
For this purpose we can utilize firebug / xpath checker to find out is there any id / name exists for the object we are going to
perform action upon. Then write the code as below:

driver.findElement(By.xpath("//a[@href='CustomerInfo.htm']")).click();

In the above line of code driver could be FirefoxDriver, InternetExplorerDriver, ChromeDriver, HtmlUnitDriver, etc. On one of
these browsers we are going to find an element and then click as per the code.

findElement is an API provided by the webdriver which requires argument By.xpath. The xpath can be replaced by one of
the below methods if we need to identify the element with any other attributes such as css, name, classname, etc:

1. className
2. cssSelector
3. linkText
4. name
5. partialLinkText
6. tagName
7. xpath
8. id

To understand the above methods one needs the basic understanding of the HTML. Id, name, input, type, a, etc are the HTML
tags / attributes. Using these HTML tags and attributes xpath can be constructed and this I have already explained in one of
my earlier posts (How to write xpath)

Type value in an Editbox

Have a look at the below line of code.

driver.findElement(By.name("FirstName")).sendKeys("Google");

Here the webdriver finds the object first with findElement API and then keys in the value with sendKeys method.

Select a value from the dropdown


To select a value from a dropdown, follow the below steps:

1. Declare a List and assign all the values of dropdown using findElements method
2. Use a for loop to go through the elements one by one
3. Using an IF condition match the required option
4. Click the required option (.setSelected is deprecated)

Use the below code and put that into a function which does the job.

public static void selectValue(String valToBeSelected){

List options = driver.findElements(By.tagName("option"));

for (WebElement option : options) {

if (valToBeSelected.equalsIgnoreCase(option.getText())){

option.click();

call the static method wherever necessary selectValue(Texas) will select the value Texas from the dropdown country.

Check / Uncheck a checkbox

To Check / Uncheck a checkbox, the object needs to be identified using findElement method and then just click. To find out
whether the checkbox is checked or not utilize the method element.isSelected()

WebElement kancheck = driver.findElement(By.name("kannada"));

kancheck.click();

System.out.println(kancheck.isSelected());

Above code snippet will first click the checkbox named kannada and then verifies whether it is clicked or not.

Select a radio button

Follow the same steps which are used in Checkbox to select a radio button and then verify the status using isSelected() method.

WebElement gender = driver.findElement(By.xpath("//input[@name='male']"));

gender.click();

System.out.println(gender.isSelected());
elect value in weblist using WebDriver

The below example open spicejet.com and select Goa in from list
FirefoxDriver fd=new FirefoxDriver();
fd.get("http://www.spicejet.com");
Thread.sleep(5000);

WebElement ListBox = fd.findElement(By.id("from1Select"));


List options = ListBox.findElements(By.tagName("option"));
for(WebElement option : options)
{
if(option.getText().equals("Goa"))
{
option.click();
break;
}
}
Aslo it works like this

fd.findElement(By.xpath("//select[@id='from1Select']/option[@value='Goa'"]")).click();

switch to multiple windows WebDriver

set fxdriver=new FirefoxDriver();

///get all window handles


Set wh=fxdriver.getWindowHandles();

////get the iterator


Iterator ite=wh.iterator();

///get main window name


String mainwind=ite.next().toString();

///get the next window name


String newwname=ite.next().toString();

////switch to next window


fxdriver.switchTo().window(wname);

//////////////////////////do all the action required

///////focus back to main window


fxdriver.SwitchTo().Window(mainwind)

Selenium Webdriver
Webdriver is the latest version of Selenium. From Selenium 2.x version of series has Selenium WebDriver and RC also for
backward compatibility. Webdriver has more libraries and features to work with Compared with RC. Like RC there is no need of
selenium server to run if we are working with Webdriver. Webdriver libraries will directly interact with browser.

Webdriver is purely object oriented as compare to Selenium RC.


Interacts natively with browser where as Selenium RC is JavaScript based.
Webdriver supports for testing iPhone and Android applications but Selenium RC is not supported.
Implements HTMLUnit driver which makes test execution really fast.
Like RC supports for all the browsers and also supports for latest version of Firefox & IE.
But it is complex and a bit large API when compared to RC
While referring elements using xpath no need to append xpath=\\ like in RC

To Develop Webdriver Scripts and Execute


Same Configuration done for RC is sufficient like
Eclipse
Java Installation
Selenium 2.x version Libraries and these are added in Eclipse

Some of the Webdriver methods

get(url) navigate to the url specified.


getTitle() - Get the title of the current browser.
getPageSource() - Get the source code of the current browser /Page .
close() - Closes the current browser.
quit() - Close all associated browsers.
getCurrentUrl() - Get the URL of the current webpage.
getWindowHandle()-Return an handle of the window that uniquely identifies it within this driver instance.
navigate("url")--allowing the driver to access the browser's history and to navigate to a given URL
navigate().back()--Move back to previous page in the browser's history.
navigate().forward()--Move to forward page in the browser's history
navigate().refresh()--Refresh the current page
switchTo()--Send future commands to a different frame or window / change focus to specified window / frame

Data Driven Testing in WebDriver Using jxl


Posted on February 9, 2013 by Dwarika Dhish Mishra

Data Driven Testing through WebDriver using jxl


Prerequisite

1- Download jxl jar file and add it in to path


2- Junit jar file
3- Selenium-server-standalone-2.x.jar
Add these three jar file in build path and to read more about adding jar file read my last post Configuring Selenium Webdriver in
Eclipse with Testng plugin installation .

In general when we say Data Driven then only thing that should come in to mind is that input is going to be read from some xls
file, xml,csv or some other table oriented file and might be output would also be written in xls,xml or csx file. All read data
from various files are stored in variables and finally used by scripts to run the test cases.
Data Driven testing is mainly divided in two part
1- Reading data and storing in to variable
2- Using data stored in variable in to some generic script.

Reading Data and storing in to variable


Since Webdriver dont have structure like other automation tools like QTP to have its own Data table to store data to run tests
in Data Driven framework. So we normally two jar file(Binaries) JXL(Java Excel API) and Apache POI to make Data Driven test
framework for WebDriver.
I am using JXL binary in this example. so for reading data from xls file we need to follow these step

1- Opening Excel file , so to open excel file we would use these two line. I have created one excel file r.xls and now we would
write code to reach to this file and to open this excel sheet.
import java.io.FileInputStream;
import jxl.Workbook;

FileInputStream fi = new FileInputStream(C:\\Users\\kaushal\\Desktop\\r.xls);

Workbook w = Workbook.getWorkbook(fi);

In above code
FileInputStream obtains input bytes from a file in a file system

2- Opening worksheet

import jxl.Sheet;

Sheet sh = w.getSheet(0); or w.getSheet(Sheetnumber)

Here 0 as argument states about firest sheet, if we want to read second sheet then we may use 1 in place of 0

3- Reading data
code used is

String variable1 = s.getCell(column, row).getContents();

These are 3 steps that is used in reading data from excel sheet

In my example or code I am going to write code to test login to Gmail for various user and Username and Password is save in
excel sheet and we will keep reading this data by using loop and we would store these data in two variable username and
password

package com.testng;
import java.io.FileInputStream;
//import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Data{
Sheet s;
WebDriver driver;
@Before
public void setUp()
{
driver = new FirefoxDriver();
}
@Test
public void searchGoogle() throws Exception
{
FileInputStream fi = new FileInputStream("C:\\Users\\kaushal\\Desktop\\r.xls");
Workbook w = Workbook.getWorkbook(fi);
s = w.getSheet(0);
for(int row=1; row <=s.getRows();row++)
{
String username = s.getCell(0, row).getContents();
System.out.println("Username "+username);
driver.get("http://www.gmail.com");
driver.findElement(By.name("Email")).sendKeys(username);
String password= s.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.name("Passwd")).sendKeys(password);
driver.findElement(By.name("signIn")).click();
}
}
@After
public void tearDown()
{
driver.close();
driver.quit();
}
}

Selenium Web Driver code

Selenium WebDriver CODE

INDEX

1. Browser Back and Forward (NAVIGATION)


2. Handling DRAG and DROP
3. Making Single Select in Drop down (Option List)
4. Making Single Select in Drop down (By INDEX, VALUE, TEXT)
5. Multiple Select List Box Window
6. Multiple Select List Box Window - DESELECT
7. iFRAMES - How to handle Frames in Web Driver
8. iFRAMES - How to perform action in Frames
9. iFRAMES - How to switch to a perticular Frame through index
10. TABS / New Window
11. CALENDAR popups
12. Drop Down MENU
13. Context Click (Right Click)
14. JAVA SCRIPT example
15. Multiple Elements
16. Other Browser (Internet Explorer)
17. Other Browser (Chrome)
18. PROXY settings.
19. Page Onload authentication
20. File Download
21. File Upload
22. Java Alert

1.Browser Back and Forward (NAVIGATION)

Steps to implement Browser back and forward through Selenium Web Driver

1. Create Driver for any Browser(Mozilla)

2. Go to the URL

3. Navigate to some page in website.

4. Use Selenium code to Navigate Back to Main Page.

CODE: driver.navigate().back();

driver.navigate().forward();

Example

WebDriver driver =new FirefoxDriver();


driver.get("http://seleniumhq.org/");

driver.findElement(By.linkText("Download")).click();

Thread.sleep(3000); //delay

driver.navigate().back();

driver.navigate().forward();

------------------------------------------------------------------------------------------------------------------------------

2.Handling DRAG and DROP

Steps to Handle Drag and Drop through Selenium Web Driver

1. Create Driver for any Browser(Mozilla)

2. Go to the URL

3. Create an Action object for Driver

4. Fetch and create WebElement object for the SOURCE element.

5. Fetch and create WebElement object for the DESTINATION element.

6.Perform ACTION
1.Click and Hold the source WebElement

2.Move to destination WebElement

3.Release the Element.

Example

WebDriver driver = new FirefoxDriver();


driver.get("http://www.ericbieller.com/examples/dragdrop/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Actions act = new Actions(driver);


WebElement src = driver.findElement(By.xpath("//div[@id='items']/div[1]"));
WebElement des = driver.findElement(By.id("trash"));

act.clickAndHold(src).build().perform(); //For each action we need to build and Perform


act.moveToElement(des).build().perform();
act.release(des).build().perform();
------------------------------------------------------------------------------------------------------------------------------

3.Making Single Select in Drop down (Option List)

Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Create an Select object for the Drop Down Element object.
5. Create a List and collect all Options through Select Object.
6. Create a Iterator object for the List.
7. Get the size of the List.
8. Loop through and check for required element.

Example

WebElement element = driver.findElement(By.name("selectedCustomer"));


Select dd= new Select(element);
List<WebElement> allOptions= dd.getOptions();

//To go through the list, we can use an Iterator.


//Iterator should be of the same type as the List
//which is WebElement in this case.

Iterator<WebElement> it = allOptions.iterator();
//Using while loop, we can iterate till the List has
//a next WebElement [hasNext() is true]
//number of items in the list
System.out.println(allOptions.size());
while(it.hasNext()){
//When you say it.next(), it points to a particular
//WebElement in the List.
WebElement el = it.next();
//Check for the required element by Text and click it
if(el.getText().equals("mango")){
System.out.println(el.getAttribute("value"));
el.click();
}
}

------------------------------------------------------------------------------------------------------------------------------

4.Making Single Select in Drop down (By INDEX, VALUE, TEXT)

Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by INDEX
6. Select by VALUE
7. Select by VISIBLE TEXT

Example

WebElement customerdd = driver.findElement(By.name("customerProject.shownCustomer"));


//convert the element to select object

Select cust = new Select(customerdd);

cust.selectByIndex(1); //Select by Index

Thread.sleep(3000);

cust.selectByValue("2"); //Select by Value

Thread.sleep(3000);

cust.selectByVisibleText("mango"); //Select by Visible Text

------------------------------------------------------------------------------------------------------------------------------

5.Multiple Select List Box Window

Steps to make Multiple Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index)
6. Select by Index(End index)

Example

WebElement userdd = driver.findElement(By.name("users"));


Select usr = new Select(userdd);
usr.selectByIndex(0); //Select by Index(From Start location)
usr.selectByIndex(2); //Select by index(To End Location)

------------------------------------------------------------------------------------------------------------------------------

6.Multiple Select List Box Window - DESELECT

Steps to make Deselect in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)

2. Go to the URL

3. Fetch the Drop Down element and create an object as WebElement.

4. Convert the Drop Down Element in to Select object.

5. Select by Index(Start index)

6. Select by Index(End index)

Example

WebElement userdd = driver.findElement(By.name("users"));


Select usr = new Select(userdd);
usr.selectByIndex(0);
usr.selectByIndex(2);

//You can deselect the options


usr.deselectAll(); //Deselect ALL selected elements
//or
usr.deselectByIndex(0); //Deselect By using Index
//or
usr.deselectByValue(value); //Deselect By using Value
//or
usr.deselectByVisibleText(text); //Deselect By using Text

------------------------------------------------------------------------------------------------------------------------------

7.iFRAMES - How to handle Frames in Web Driver

Steps to get Source of each iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)

2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Loop though and print the Source of each Frame

Example

/*times of india website - multiple frames*/

driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

List<WebElement> frms= driver.findElements(By.tagName("iframe")); //Frame List


System.out.println(frms.size());
for(int i=0;i<frms.size();i++)
{
System.out.println(frms.get(i).getAttribute("src"));
}
------------------------------------------------------------------------------------------------------------------------------

8.iFRAMES - How to perform action in Frames

Steps to perform Action in iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)

2. Go to the URL
3. Fetch iFrame element and create an Web Element object.
4. Using iFrame Web Element object, switch to IFrame.
5. Perform SendKeys/ Click action in iFrame.
Example

WebElement ifr = driver.findElement(By.xpath("//iframe[@src='/poll.cms']"));


driver.switchTo().frame(ifr); //Switch to iFrame
driver.findElement(By.id("mathuserans2")).sendKeys("8"); //Perform Action in iFrame

------------------------------------------------------------------------------------------------------------------------------

9.iFRAMES - How to switch to a perticular Frame through index

Steps to switch to perticular iFrame by index through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)

2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Switch to required iFrame through index.

Example

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

List<WebElement> frms= driver.findElements(By.tagName("iframe"));


System.out.println(frms.size());
driver.switchTo().frame(0);
driver.findElement(By.id("clicktripad")).click();

------------------------------------------------------------------------------------------------------------------------------

10. TABS / New Window

When Browser opens in a new window or in a new tab, Web Driver cannot shift the control to the new Window/ Tab. We need
to collect the window handles in a page. Whenever a new window opens we need to iterate and shift to the latest window
handle.

TABS/New Window - 1

Steps to iterate through the Window Handles

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Collect Window Handles through Set<String>
4. Create an iterator to iterate through Window Handles.
5. At First iterator will not be pointing to any Window Handle, only First increment Points to First Window Handle, Second
increment Points to second iterator.

Set<String> windowHandles = driver.getWindowHandles();


Iterator<String> it = windowHandles.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
------------------------------------------------------------------------------------------------------------------------------

TABS/New Window - 2

When two browsers are opened and Web Driver need to shift the control from Parent Window to Child Window.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Collect Window Handles through Set<String>
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.

Set<String> windowHandles = driver.getWindowHandles();


Iterator<String> it = windowHandles.iterator();

String parentBrowser= it.next();


String childBrowser = it.next();
driver.switchTo().window(childBrowser);

------------------------------------------------------------------------------------------------------------------------------

TABS/New Window - 3

When second browser is closed/you close it and Web Driver need to shift the control from Child Window to Parent Window.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Collect Window Handles through Set<String>
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.
8. When Child browser get closed, Switch from Child browser to Parent Window.

Set<String> windowHandles = driver.getWindowHandles();


Iterator<String> it = windowHandles.iterator();

String parentBrowser= it.next();


String childBrowser = it.next();
driver.switchTo().window(childBrowser);
Thread.sleep(3000);

driver.close(); //close the current window(Child Browser)


driver.switchTo().window(parentBrowser); //Switch to Parent Browser

------------------------------------------------------------------------------------------------------------------------------

11. CALENDAR popups

Calendar PopUp - 1

Normal Calender(current month) Popup can be handled in the following way.

1. Create Driver for any Browser(Mozilla)

2. Go to the URL
3. Fetch the Calender element and click to open.
4. Fetch the required date through xpath and click.

/*IRCTC calendar*/
driver.findElement(By.id("calendar_icon1")).click();
driver.findElement(By.xpath("//div[@id='CalendarControl']/table[tbody[tr[td[text()='October
2012']]]]/descendant::a[text()='5']")).click();

------------------------------------------------------------------------------------------------------------------------------
Calendar PopUp - 2 (Customized wait)

In a Calender if we want to click on future month which is not currently displayed, we need to click on next link until we get the
required month.
This can be done by writing Customized wait. Check for particular date element in each month, if not found move to next
month.

/*makemytrip calendar*/
driver.get("http://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("deptDateRtripimgExact")).click(); //find Calendar
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
boolean flag=true;
while(flag){
try {
WebElement el = driver.findElement(By.xpath("//div[contains(@class,'ui-datepicker-group') and
descendant::span[text()='March']]/descendant::a[text()='5']")); // Required future date
if(el !=null) //Check if the required date element is found or not
{
el.click(); // if required Date is found, then click the date
flag=false;
}
}
catch (Exception e) { //Catches exception if no element found
try {
Thread.sleep(500);
driver.findElement(By.xpath("//a[@title='Next']")).click(); //Click on next month
}
catch (InterruptedException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

------------------------------------------------------------------------------------------------------------------------------

12. Drop Down MENU

In order to click on an menu item, first we need to move the mouse over Parent menu, later we can click on any of the Menu
child item.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)


2. Go to the URL
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action object for Driver
5. Through Action object, move to Parent element.
6. Give a Delay for menu items to be displayed.
7. Fetch the Child item through xpath and Click on it.

WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));


Actions act = new Actions(driver); // Create an Action object
//move to the parent menu item

act.moveToElement(parentMenu).build().perform();

Thread.sleep(3000); //wait till the child items are displayed

driver.findElement(By.linkText("Bharat Tirth")).click();

------------------------------------------------------------------------------------------------------------------------------

13. Context Click (Right Click)

We can use keyboard keys to Make a Right Click.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).


2. Go to the URL.
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action Object for Driver.
5. Through Action Object, make a Context Click on Menu Parent object.
6. Through Action Object, send keys for ARROW_DOWN/ARROW_UP/Keys.ENTER.

Example

WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));

Actions act = new Actions(driver); //Create Action object for Driver

act.contextClick(parentMenu).build().perform(); //Context Click

act.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ENTER).build().perform();

------------------------------------------------------------------------------------------------------------------------------

14. JAVA SCRIPT example

We can use java script command to perform actions.

We can write code to fill up the text box through java script.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).


2. Go to the URL.
3. Create Java Script executor object for the Driver.
4. Store the Java Script command in a String Variable.
5. Java Script Executor object executes the command in the Variable.

JavascriptExecutor js = (JavascriptExecutor) driver;


String jsCmd = "document.getElementsByName('city')[0].value='ban'";
js.executeScript(jsCmd);

------------------------------------------------------------------------------------------------------------------------------

15. Multiple Elements

We can count the number of links present in the page. We can also print the link text of each Web link.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).


2. Go to the URL.
3. Fetch elements with tag //a in the entire page, store it in a List.
4. Get the count of Links present in the Page.
5. Loop through the links and print the Attributes

List<WebElement> allLinks= driver.findElements(By.xpath("//a"));


//display the count of links in the page
System.out.println(allLinks.size());
//display the text for each link on the page
for(int i=0;i<allLinks.size();i++)
{
//display href for each link
System.out.println(allLinks.get(i).getAttribute("href"));
//display text for each link
System.out.println(allLinks.get(i).getText());
//perform click action
allLinks.get(i).click();

------------------------------------------------------------------------------------------------------------------------------

16. Other Browser (Internet Explorer)

Using Internet Explorer with Web Driver.

Please follow the steps mentioned below.


1. Set System Property for the Driver and give path of the IE Driver.
2. Create an Web Driver Object.
3. Open an URL

System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");

WebDriver driver =new InternetExplorerDriver();


driver.get("www.google.com");

------------------------------------------------------------------------------------------------------------------------------

17. Other Browser (Chrome)

Using Chrome with Web Driver.

Please follow the steps mentioned below.

1. Set System Property for the Driver and give path of the Chrome Driver.
2. Create an Web Driver Object.
3. Open an URL

System.setProperty("webdriver.chrome.driver", "D:\\sel\\browserdrivers\\Chromedriver.exe");

WebDriver driver = new ChromeDriver();


driver.get("www.google.com");

------------------------------------------------------------------------------------------------------------------------------

18. PROXY settings.

Please follow the steps mentioned below.

1. Import Selenium.Proxy

2. Create a Profile object for Firefox

3. Create a string variable with value.

4. Create a Proxy object.

5. Set the values through proxy.

6. Set the proxy preference to proxy object using profile object.

7. Pass the profile object to Firefox Driver.

import org.openqa.Selenium.Proxy

FirefoxProfile profile = new FirefoxProfile();


String PROXY = "xx.xx.xx.xx:xx";
Proxy proxy = new Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);

------------------------------------------------------------------------------------------------------------------------------

19. Page Onload authentication

Sometimes when you are Automating Web pages, you may come across Page onload Authentication window. This window is
not java popup/div. It is windows popup. Selenium directly cannot handle this windows popup.
Hence we use Autoit sowftware tool. Through Selenium we can handle this situation using Autoit.

Please follow the steps mentioned below.

1.Download Autoit from the following URl


( http://www.autoitscript.com/site/autoit/downloads/ )

2.Install downloaded software.

3. Open Script Editor

Start=>ProgramFiles=>AutoIt =>SciTE Script Editor.

4.Open Object Identifier.

Start=>ProgramFiles=>AutoIt =>AutoIt Window Info.

5.Drag and Drop finder tool in AutoIt Window Info, to the Window you need to identify.

6.Collect the Title Name of window from (AutoIt Window Info.)

7.Write the Script in the Editor.

----------------------------------------------------AUTOIT CODE-----------------------------------------------------

WinWaitActive("Authentication Required")

Send("admin")

Send("{TAB} admin{TAB} {ENTER}")

------------------------------------------------------------------------------------------------------------------------------

8.Save the file as default save.(Authentication1.exe)

9.RUN/Compile the SCRIPT, it creates an exe.

10.Mention the exe path in the Program before creation of Driver.

EXAMPLE:

Process P = Runtime.getRuntime().exec("D:\\java_prj\\SELENIUM WEBDRIVER\\AUTOIT\\Authentication1.exe");


WebDriver driver = new FirefoxDriver();
driver.get("http://192.168.1.1");
------------------------------------------------------------------------------------------------------------------------------

20. File Download

Please follow the steps mentioned below.

1. Create a PROFILE object of Browser.


2. Set Preference, by giving Download destination Directory.
3. Set Preference, by giving Default Folder. 0 => Desktop, 1=>System Default Location, 2 => Indicates a custom Folder Location
4. Set Preference, A comma-separated list of MIME types to save to disk without asking what to use to open the file. Default
value is an empty string.

After coding the above mentioned steps, now start the driver and click on Download button/link.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the Download web element and click.

FirefoxProfile Prof = new FirefoxProfile();


Prof.setPreference("browser.download.dir", "D:\\java prj");
Prof.setPreference("browser.download.folderList", 2);
Prof.setPreference("browser.helperApps.neverAsk.saveToDisk","application/zip");

WebDriver driver = new FirefoxDriver(Prof);


driver.get("http://seleniumhq.org/download/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
driver.findElement(By.xpath("//a[@name='client-drivers']/table/tbody/tr[1]/td[4]/a")).click();

------------------------------------------------------------------------------------------------------------------------------

21. File Upload

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).


2. Go to the URL.
3. Store the Source path of file in a variable.
4. Fetch the Upload web element text box and give path using variable.
5. Fetch the upload button and click

WebDriver driver = new FirefoxDriver();


driver.get("http://www.2shared.com/");
String FilePath = "C:\\Users\\abc\\Desktop\\test.xml";
driver.findElement(By.id("upField")).sendKeys(FilePath);
driver.findElement(By.xpath("//input[@type='image']")).click();
------------------------------------------------------------------------------------------------------------------------------

22. Handling JAVA ALERT

Sometimes you may get alerts as anticipated(through Insert/update/delete operation in database). These may be JAVA alerts.
Please follow the steps mentioned below to handle Alerts.

1. Create Driver for any Browser(Mozilla).


2. Go to the URL.
3. You get an alert asking to click on 'YES' or 'NO' button.
4. First Confirm if it is JAVA alert window.
5. Write a code to switch the control to Alert window.
6. In the Alert window, either ACCEPT by clicking on 'YES'
or CANCEL by clicking on 'NO'.

WebDriver driver = new FirefoxDriver();


driver.get("http://www.2shared.com/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Alert alert = driver.switchTo().alert();


alert.accept();
//or
alert.dismiss();

composing an email using selenium web driver

composing an email using selenium web driver

I tried composing an email from gmail using selenium webdriver.


I found a better way to enter text without switching frames.
Please refer to the below code.

import java.util.concurrent.TimeUnit;

//import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
//import org.openqa.selenium.WebElement;
//import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.Select;

public class composingAnEmail {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

WebDriver d1;
d1=new FirefoxDriver();
d1.get("https://mail.google.com/");
d1.findElement(By.id("Email")).sendKeys("Your mail Id");
d1.findElement(By.xpath("//*[@id='Passwd']")).sendKeys("Your password");
d1.findElement(By.id("signIn")).click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
d1.findElement(By.xpath("/html/body/div[5]/div[2]/div/div[2]/div/div/div/div[2]/div/div/div/div/div")).click();
d1.findElement(By.xpath("//textarea[@name='to']")).sendKeys("receiver's Id");
d1.findElement(By.name("subject")).sendKeys("test mail");
//I felt this method works more better than switching frames.
d1.findElement(By.xpath("//iframe[@class= 'Am Al editable']")).click();
d1.findElement(By.xpath("//iframe[@class= 'Am Al editable']")).sendKeys("Hi ! How are you ?This is my first email using
selenium webdriver.");
d1.findElement(By.xpath("//div[@class='T-I J-J5-Ji Bq nS T-I-KE L3']")).click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
d1.quit();
}
}

Deleting an email and undoing it.

I have tried deleting an email and again undoing it . I was quite successful in it .Check it out..

import java.util.concurrent.TimeUnit;

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.Select;

public class deletingAnEmail {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

WebDriver d1;
d1=new FirefoxDriver();
d1.get("https://mail.google.com/");
d1.findElement(By.id("Email")).sendKeys("Your Id");
d1.findElement(By.xpath("//*[@id='Passwd']")).sendKeys("Your password");
d1.findElement(By.id("signIn")).click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// This is for deleting..

WebElement checkbox=d1.findElement(By.id(":mf"));
checkbox.click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
d1.findElement(By.xpath("/html/body/div[5]/div[2]/div/div[2]/div/div[2]/div/div/div/div/div/div/div/div
/div/div[2]/div[3]")).click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//This is for undoing..

d1.findElement(By.xpath("//span[@id='link_undo']")).click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
d1.quit();
}

Deleting multiple emails and undoing it.

Once you got to know how to check a box, ,It is easy to click on one or multiple checkboxes.Which enables us to automate
options like deleting multiple emails.

Here is the code below:


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.Select;

public class deletingMultiplemails {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

WebDriver d1;
d1=new FirefoxDriver();
d1.get("https://mail.google.com/");
d1.findElement(By.id("Email")).sendKeys("Your ID");
d1.findElement(By.xpath("//*[@id='Passwd']")).sendKeys("Your password");
d1.findElement(By.id("signIn")).click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement checkbox1=d1.findElement(By.id(":mf"));
checkbox1.click();
WebElement checkbox2=d1.findElement(By.id(":m5"));
checkbox2.click();
WebElement checkbox3=d1.findElement(By.id(":lv"));
checkbox3.click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
d1.findElement(By.xpath("/html/body/div[5]/div[2]/div/div[2]/div/div[2]/div/div/div/div/div/div/div/div
/div/div[2]/div[3]")).click();
//d1.findElement(By.xpath("//div[@class='oZ-jc T-Jo J-J5-Ji T-Jo-Jp']")).click()
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
d1.findElement(By.xpath("//span[@id='link_undo']")).click();
d1.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
d1.quit();
}

How to click on elements in iframe using Selenium web driver?

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.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;

public class iFrameTest {

public static void main(String[] args) throws InterruptedException {

// ProfilesIni allProfiles = new ProfilesIni();


// FirefoxProfile myProfile = allProfiles.getProfile("MyTestProfile");
// myProfile.setPreference("capability.policy.default.Window.frameElement.get","allAccess");
// WebDriver myTestDriver = new FirefoxDriver(myProfile);
WebDriver myTestDriver = new FirefoxDriver();
myTestDriver.manage().window().maximize();

myTestDriver.get("http://tinyurl.com/cb3lbho");
Thread.sleep(5000L);

try {

List<WebElement> AlliFrameID = myTestDriver.findElements(By.tagName("iframe"));


System.out.println(AlliFrameID.size());
for(int i=0;i<=AlliFrameID.size();i++){
System.out.println(AlliFrameID.get(i).getAttribute("id"));
}
} catch (Exception e) {

myTestDriver.switchTo().frame("ifrm");
myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[2]/input")).click();
System.out.println(myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[1]/input")).getAttribute("value"));

myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[3]/input")).click();
System.out.println(myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[1]/input")).getAttribute("value"));

myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[3]/input")).click();
System.out.println(myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[1]/input")).getAttribute("value"));

myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[3]/input")).click();
System.out.println(myTestDriver.findElement(By.xpath("//*[@id='ifrmTest']/p[1]/input")).getAttribute("value"));

myTestDriver.switchTo().defaultContent();
myTestDriver.findElement(By.xpath("//*[@id='testForm']/p/input[1]")).sendKeys("Online selenium Training");

myTestDriver.findElement(By.xpath("//*[@id='testForm']/p/input[2]")).click();

How to select an item in Listbox using Selenium Webdriver

There are many ways you can do this.

Below are my best ways to select a list item from a listbox:

Option 1:
//First find the Listbox element as WebElement.
WebElement o_Item= driver.findElement(By.id("uw_flight_origin_input_d"));
//Then select the list item from the WebElement
o_Item.findElement(By.xpath("//option[contains(text(),'" + nameYouWant + "')]")).click();

Option 2:
Select menu = new Select(driver.findElement(By.id("uw_flight_origin_input_d"))); menu.selectByVisibleText(nameYouWant);

A complete sample code is here:


import org.openqa.selenium.support.ui.Select;
WebDriver driver=new FirefoxDriver();
driver.get("http://www.expedia.co.in/");
String nameYouWant="Hyderabad";
WebElement o_Item= driver.findElement(By.id("uw_flight_origin_input_d"));
o_Item.findElement(By.xpath("//option[contains(text(),'" + nameYouWant + "')]")).click();
/*Select menu = new Select(driver.findElement(By.id("uw_flight_origin_input_d")));
menu.selectByVisibleText(nameYouWant);*/

In the same way how to select a checkbox or radio button based on a value:
Here is a sample HTML code for an application
<html>
<head></head>
<body>
<form>
<Input type="radio" name="sex" value="male">Male<br>
<Input type="radio" name="sex" value="female">Female<br>
Likes :<br>
<input type="checkbox" name="likes" value="cars">Cars<br>
<input type="checkbox" name="likes" value="bikes">Bikes<br>
<input type="checkbox" name="likes" value="Movies">Movies<br>
</form>
</body>
</html>

WebDriver driver=new FirefoxDriver();


driver.get("FilePath);

driver.findElement(By.xpath("//input[@name='sex' and @value='female']")).click();

driver.findElement(By.xpath("//input[@name='likes' and @value='Movies']")).click();

How to click on a element with specific Text

How we will click on a element(Link/button/any element) with a specific Text.

In the below example i open Yahoo Website and look for an element called "Mail", if it found it clicks on the link else it reports
Exception saying String not found.

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

public class ClickLinkByText


{
public static void main(String[] args)
{
String s_URL="http://www.yahoo.com";
String s_SearchLink="Mail";
WebDriver driver=new FirefoxDriver();
driver.get(s_URL);
try
{
driver.findElement(By.xpath("//*[@title='"+s_SearchLink+"']")).click();
}
catch(Exception e)
{
System.out.println("Searched string not found");
};
}
}

How to check the object existance

Here in the below code, i am checking for an object existence.

//Max_TimeOut variable holds the time in seconds for the maximum time to wait before the control flows to
NoSuchElementException block.
int Max_TimeOut=60;
public boolean isObjExists(WebDriver driver,By locator)
{
//I am putting the code in try catch because if the object does not exist, it throws exception.
try
{
//Before throwing exception, it will wait for the Max_timeout specified
WebDriverWait wait=new WebDriverWait(driver,Max_TimeOut);
wait.until(ExpectedConditions.elementToBeClickable(locator));
//If the element found, then it returns true
return true;
}
catch(NoSuchElementException exception)
{
//If the element is not found, then it returns false
return false;
}

This function can be invoked in like below:


By locator=By.name("Email");
if(obj.isObjExists(driver, locator))
{
Reporter.log("Object exists");
WebElement uNameElement=driver.findElement(locator);
uNameElement.sendKeys("abcd");
}
else
{
Reporter.log("Object does not exist");
}

Using Selenium Web Driver to send e-mail with GMail

I'm trying to learn more about using Selenium Web Driver for testing web applications, so I've spent a good chunk of time this
weekend doing all kinds of little things with websites, just to learn my way around.
The hardest one I had was sending an e-mail with GMail. That 'Compose' button was tricky for me at first.

Here is the result of my efforts, just in case anyone ever wants to automate GMail with Selenium, I hope it helps you out.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace TestingSeleniumGmail
{
[TestClass]
public class FillFormIntegrationTest
{
public static string BaseUrl = "http://www.gmail.com";
public const int TimeOut = 30;

[TestMethod]
public void CanFillAndSubmitFormAfterLogin()
{
var driver = new FirefoxDriver();

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(TimeOut));

driver.Navigate().GoToUrl(BaseUrl);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27 28 29 30 31 32 var loginBox = driver.FindElement(By.Id("Email"));
loginBox.SendKeys("email.address@gmail.com");
33 34 35 36 37 38 39 40 41 42 43 44 45 46
47 48 49 50 51 52 53 var pwBox = driver.FindElement(By.Id("Passwd"));
pwBox.SendKeys("!SuperSecretpassw0rd");

var signinBtn = driver.FindElement(By.Id("signIn"));


signinBtn.Click();

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(15));

driver.SwitchTo().Frame("canvas_frame");

var composeBtn = driver.FindElement(By.CssSelector("div[class='T-I J-J5-Ji T-


I-KE L3']"));
composeBtn.Click();

var toBox = driver.FindElement(By.CssSelector("textarea[class='dK nr']"));


toBox.SendKeys("another.email@somedomain.com");

var subjBox = driver.FindElement(By.CssSelector("input[class='ez nr']"));


subjBox.SendKeys("This is a test");

var msgBox = driver.FindElement(By.CssSelector("textarea[class='Ak


aXjCH']"));
msgBox.SendKeys("This is a test email sent via Selenium Web Driver");
var sendBtn = driver.FindElement(By.CssSelector("div[class='T-I J-J5-Ji Bq nS
T-I-KE L3']>b"));
sendBtn.Click();

}
}
}
The Below code searches for an item in the drop down and selects it

public void Dropdown(String eleproperty, String value) {


WebElement element = driver.findElement(By.id(eleproperty));
if (element.isEnabled()) {
WebElement dropdown = driver.findElement(By.id(eleproperty));
Select select = new Select(dropdown);
String str = dropdown.getText();
List<WebElement> options = select.getOptions();
for (WebElement we : options) {
if (we.getText().equals(value)) {
we.click();
break;
}

xtract all links from a webpage using webdriver for selenium automation testing

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;

public class dadabhagwan_LearnSeleniumWithJasmine {

public static void main(String[] args) throws InterruptedException {

WebDriver myDriver = new FirefoxDriver();


myDriver.get("http://satsang.dadabhagwan.org/");

/*Extract all links from the webpage using selenium webdriver*/


List all_links_webpage = myDriver.findElements(By.tagName("a"));

/*Print total no of links on the webpage*/


System.out.println("Print total no of links on the webpage---------------------------------------------");
System.out.println(all_links_webpage.size());

/*Print text of all links*/


System.out.println("Print text of all links------------------------------------------------------------");
for(int i=0;i<all_links_webpage.size();i++){< p=""></all_links_webpage.size();i++){<>
System.out.println(all_links_webpage.get(i).getText());
}
/*Print Links*/
System.out.println("Print Links------------------------------------------------------------------------");
for(int i=0;i<all_links_webpage.size();i++){< p=""></all_links_webpage.size();i++){<>
System.out.println(all_links_webpage.get(i).getAttribute("href"));
}

/*Extract all links from the part of the webpage using selenium webdriver*/
System.out.println("Extract all links from the part of the webpage using selenium webdriver----------------------
-------");
List myList = myDriver.findElement(By.xpath("//*[@id='Flot']")).findElements(By.tagName("a"));

System.out.println("total no links on specific part of webpage---------------------------------------------------");


System.out.println(myList.size());

System.out.println("Text of the link for specific part of webpage--------------------------------------------------");


for(int i =0; i< myList.size();i++){
System.out.println(myList.get(i).getText());

asic Functionalities of webdriver Part - II

Basic functionalists of selenium webdriver

package webdriver;

import java.net.URL;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Webdriver_2 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver d=null;
try
{
Capabilities c=DesiredCapabilities.firefox();
d = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), c);

d.get("http://localhost:8080/saome/webdriver/popup.jsp");
/**
* Switches to the element that currently has focus, or the body element if this cannot be detected.
*/
WebElement wb= d.switchTo().activeElement();
wb.click();
Thread.sleep(5000);

/**
*Selects either the first frame on the page, or the main document when a page contains iframes.
*/
WebDriver frmae=d.switchTo().defaultContent();

/**
*
* Return an opaque handle to this window that uniquely identifies it within this driver instance. This can be used to switch
to this window at a later date
*/

String windowHandle= d.getWindowHandle();


d.get("http://localhost:8080/saome/webdriver/frame.jsp");
/**
* Select a frame by its name, id or (zero-based) index. To select sub-frames, simply separate the frame names/IDs/indexes
by dots. As an example "main.child" will select the frame with the name "main" and then it's child "child". If the given string
represents an integer number, then it will be used to select a frame by its (zero-based) index.
*/
WebDriver frame= d.switchTo().frame("f1");
frame.findElement(By.name("id1")).clear();
d.switchTo().window(windowHandle);
frame= d.switchTo().frame("f2");
frame.findElement(By.name("id2")).clear();
d.switchTo().window(windowHandle);
d.switchTo().frame(d.findElement(By.name("f1")));
frame.findElement(By.name("id1")).sendKeys("guruashant");
d.close();

/**
* Following code handles alert,confirm and prompt.
*/
Capabilities c=DesiredCapabilities.firefox();
d = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), c);
d.get("http://localhost:8080/saome/prompt.jsp");
d.findElement(By.name("id1")).click();
Alert a= d.switchTo().alert();
System.out.println("Text="+a.getText());
a.sendKeys("gurushant");
a.accept();

d.findElement(By.name("id2")).sendKeys("");

d.findElement(By.name("id1")).click();
a= d.switchTo().alert();
System.out.println("Text="+a.getText());
a.sendKeys("gurushant");
a.dismiss();
d.close();

d=new RemoteWebDriver(new URL("http://localhost:4444/wd/hub") ,DesiredCapabilities.firefox());


d.get("http://localhost:8080/saome/sample.jsp");
JavascriptExecutor js=(JavascriptExecutor)d;
/**
* Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be
executed as the body of an anonymous function.
*/
Object str=js.executeScript("return document.title");
System.out.println("Title=="+str);

d.get("http://localhost:8080/saome/webdriver/popup.jsp");
WebElement ele= d.findElement(By.name("id1"));
ele.click();

Iterator<String> newhandler=d.getWindowHandles().iterator();
String parent=null,child=null;
if(newhandler.hasNext())
{
parent=newhandler.next();
child=newhandler.next();
}

WebDriver myd= d.switchTo().window(child); //here you can also specify window name.
myd.findElement(By.name("q")).sendKeys("auto");
d.switchTo().window(parent);
d.quit();//closes all open window and unregisters to the hub

/**
* Following code shows how to automate dropdown in webdriver
*/
d=new RemoteWebDriver(new URL("http://localhost:4444/wd/hub") ,DesiredCapabilities.firefox());
d.get("http://localhost:8080/saome/multiselection.jsp");
Select ss=new Select(d.findElement(By.id("id1")));
ss.selectByIndex(1);
ss.selectByVisibleText("Dev");
ss.selectByValue("auto");
List<WebElement> options= ss.getAllSelectedOptions();
ss.deselectByIndex(1);
ss.deselectByValue("auto");
ss.deselectByVisibleText("Dev");
ss.selectByVisibleText("Dev");
ss.deselectAll();

} catch (Exception e1) {


// TODO Auto-generated catch block
d.close(); //closes current window and unregisters to the hub
e1.printStackTrace();

}
}

Basic Functionalities of webdriver Part - I

Some of the basic functionalists of webdriver.

package webdriver;

import java.awt.Toolkit;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import javax.tools.Tool;

import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Navigation;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class WebDriverFun {

/**
* Webdriver basic functionalities
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Capabilities c=DesiredCapabilities.firefox();
WebDriver d=null;
try {
d = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), c);

} catch (MalformedURLException e1) {


// TODO Auto-generated catch block
e1.printStackTrace();
}
d.get("http://localhost:8080/saome/sample.jsp");

WebElement wb= d.findElement(By.name("q1"));


/*
* Clears the value of the element.
No parameters.
Return type: void
*/
wb.clear();

wb.sendKeys("This is selenium automation");


/**
* Gets attribute of an element.
*/
String attrib=wb.getAttribute("id");
System.out.println("Attribute=="+attrib);

/**
* Gets the value of a CSS property of this element.
*/
String cssValue=wb.getCssValue("background-color");
System.out.println("CSS Value="+cssValue);

/**
* It will return the "Point" object.
If you want to get the exact "x" and "y" coordinates of the element then use "getLocation()" method.
*/
Point p= wb.getLocation();
System.out.println("X="+p.x+"\t Y="+p.y);

/**
* It will returns the "Dimension" object.
If you want to get the width and Height of the specific element on the webpage then use "getsize()" method.
It returns including +6 . Suppose you have ,<input id="id4" name="id4" style="width: 200px; height: 50px;" />
It returns 206 widht , height is 56
*/
wb= d.findElement(By.name("id4"));
Dimension dim= wb.getSize();
System.out.println("Width="+dim.width+"\t Height="+dim.height);
/**
* Get the tag name of this element. Not the value of the name attribute: will return "input" for the element <input
name="foo" />.
*/
String tagName= wb.getTagName();
System.out.println("Tag Name="+tagName);

/**
* Is this element displayed or not? This method avoids the problem of having to parse an element's "style" attribute.
*/
wb= d.findElement(By.name("hid1"));
boolean isDisplayed= wb.isDisplayed();
System.out.println("is Displayed="+isDisplayed);

/**
* Is the element currently enabled or not? This will generally return true for everything but disabled input elements.
*/
wb= d.findElement(By.name("q"));
boolean isEnabled= wb.isEnabled();
System.out.println("is Enabled="+ isEnabled);

/**
* Determine whether or not this element is selected or not. This operation only applies to input elements such as
checkboxes, options in a select and radio buttons.
*/
wb= d.findElement(By.name("ch1"));
boolean isSelected= wb.isSelected();
System.out.println("is Selected="+ isSelected);

/**
* Get a string representing the current URL that the browser is looking at.
*/
String currentUrl= d.getCurrentUrl();
System.out.println("Current URL="+currentUrl);

/**
* Get the source of the last loaded page.
*/
String pageSource= d.getPageSource();
System.out.println("Page Source="+pageSource);

/**
* The title of the current page.
*/
String title=d.getTitle();
System.out.println("Title="+title);
/**
* Return an opaque handle to this window that uniquely identifies it within this driver instance.
*/
String windowHandle=d.getWindowHandle();
System.out.println("Window Handle="+windowHandle);

/**
* Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.
*/
Options op= d.manage();
op.timeouts().implicitlyWait(10, TimeUnit.SECONDS);

/**
* Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is
negative, then the script will be allowed to run indefinitely.
*/
op.timeouts().setScriptTimeout(10, TimeUnit.SECONDS);

/**
* Using navigation you can move forward,backward.
*/
Navigation nv= d.navigate();
nv.to("http://localhost:8080/saome/sample2.jsp");
nv.back();
nv.forward();

nv.back();
/**
* Maximizes the browser window
*/
d.manage().window().maximize();

/**
* Shows position of browser window
*/
p= d.manage().window().getPosition();
System.out.println("Window Postion X="+p.x+"\t Width="+p.y);

/**
* Sets the browser location
*/
d.manage().window().setPosition(new Point(100, 100));

/**
* It sets size of browser window
*/
d.manage().window().setSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width,
Toolkit.getDefaultToolkit().getScreenSize().height));
d.close();

Po

Working with Frames

java.util.List<WebElement> f = driver.findElements(By.tagName("iframe"));

System.out.println(f.size());

if(f.size()>0) {

for (WebElement frameid : f){

if(frameid.getAttribute("id").equals("frame_name"))

driver.switchTo().frame(frameid);

How to capture the full page screenshot in webdriver

In order to get the full page screenshot using web driver,


//Include these packages in the script.

import java.io.File;

import org.apache.commons.io.FileUtils;

//Add these snippet to your code.

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File("c:\\path\\filename.jpg"),true);

Use this code:

//Get Parent window handle


String winHandleBefore = _driver.getWindowHandle();
for(String winHandle : _driver.getWindowHandles()){
//Switch to chile window
driver.switchTo().window(winHandle);
}

//Do some operation on child window and get child window handle.
String winHandleAfter = driver.getWindowHandle();

//switch to child window of 1st child window.


for(String winChildHandle : _driver.getWindowHandles()){
//Switch to chile window of the 1st child window.
if(!winChildHandle.equals(winHandleBefore) && !winChildHandle.equals(winHandleAfter )){
driver.switchTo().window(winChildHandle);
}
}

//Do some operation on child window of 1st child window.


//to close the child window of 1st child window.
driver.close();

//to close the child window.


driver.close();

//to switch to parent window.


driver.switchto.window(winHandleBefore);
Reporting Results in Selenium using Java

In the automation effort Reporting result is a fundamental and a very crucial activity. Many years ago when we started moving
from Winrunner to QTP we stumbled upon the ReporterManager from www.advancedqtp.com. We used that exclusively for all
our automation reporting needs. After so many years in QTP I started exploring Selenium in 2010. After couple of months with
RC I still was not convinced about Selenium until Selenium 2 (WebDriver) was launched. I really like WebDriver and started
working on it full time. TestNG was the framework I adopted for working on Selenium. For all the reporting needs I was relying
on the TestNG in built reporting, but then I realized that in spite of its good reporting capabilities it was nowhere near the
reporting we were used with the ReporterManager.

So I and my team started working on creating a notepad result. Here is what we did
public void createNotepad(String fileName, String vGetDateForNotepad)

throws IOException {

outputNotePadResultFile = System.getProperty("user.dir") + "\\Reports\\"

+ fileName.toUpperCase() + "_" + vGetDateForNotepad + ".txt";

File f = new File(outputNotePadResultFile);

BufferedWriter wr = new BufferedWriter(new FileWriter(f));

if (f.exists()) {

f.delete();

wr.write("\t\t\t"

+ "*******************************************************");

wr.newLine();

wr.write("\t\t\t" + "Test Script Name" + "\t" + ": "

+ fileName.toUpperCase());

wr.newLine();

wr.write("\t\t\t" + "Test Executed By" + "\t" + ": "

+ (System.getProperty("user.name")).toUpperCase());

wr.newLine();

wr.write("\t\t\t" + "Browser Used Is" + "\t\t" + ": ");

wr.newLine();

wr.write("\t\t\t" + "Test Start Time" + "\t\t" + ": "

+ Calendar.getInstance().getTime().toString());

wr.newLine();

wr.write("\t\t\t" + "Test End Time: ");

wr.newLine();

wr.write("\t\t\t" + "Script Execution Time: ");


wr.newLine();

wr.write("\t\t\t" + "Script Execution Status: ");

wr.newLine();

wr.write("\t\t\t"

+ "*******************************************************");

wr.newLine();

wr.newLine();

wr.close();

stepCount = 1;

Using the above code we created a sort of reporting template which looks like this

*******************************************************

Test Script Name : XXXXXXXXX

Test Executed By : XXXXXXXXX

Browser Used Is : INTERNET EXPLORER

Test Start Time : Sun Aug 26 22:38:13 CDT 2012

Test End Time : Sun Aug 26 22:38:26 CDT 2012

Script Execution Time : 00:00:10

Script Execution Status : PASS

*******************************************************

Once the template is created the actual reporting comes into picture for which the code looks like this

protected static void writeToNotepad(String status, String expected,

String actual) {

try {
boolean append = true;

FileWriter fout = new FileWriter(outputNotePadResultFile, append);

BufferedWriter fbw = new BufferedWriter(fout);

fbw.write("Step ");

fbw.write(stepCount + "");

fbw.write(" ");

// fbw.write("(" + getDateTimeForNotepad() + ")");

fbw.write(Initialize.getDateFormat(Initialize.vDatetype9));

fbw.write(" ");

fbw.write(status.toUpperCase());

fbw.newLine();

fbw.write("----------------------------------------------------");

fbw.newLine();

fbw.write("Step Description : " + expected);

fbw.newLine();

fbw.write("Actual Result : " + actual);

fbw.newLine();

fbw.newLine();

fbw.newLine();

fbw.close();

stepCount++;

} catch (Exception e) {

System.out.println("Error: " + e.getMessage());

}
}

From here all we have to do is call the method passing the status, expected and actual

If we are calling the writeToNotepad from another method it would look like this

public void openBrowser(String URL) throws IOException {

try {

driver.navigate().to(URL);//launch Browser with the URL

//Report to Notepad, HTMl and Excel

writeToNotepad (PASS,

"Navigate to URL - " + URL,

"Navigate to URL - " + URL

+ " - Successfull".toUpperCase());

} catch (Exception e) {

writeToNotepad (FAIL,

"Navigate to URL - + URL,

"Navigate to URL Failed);//here you can use your custom message or you can
use the e.getMessage()

URL = null;

}
Here is the screen print of the result log

Reading Data from Excel in Selenium Automation

There are many ways of reading data from excel in java. For instance we can choose JExcel API or the Apache POI Java API. In
my case my team chose the java HashMap class to read test data from excel.

public static Map TestParameterMap = new HashMap<String, String>();

public void readExcelData(String excelDataSheet, String sheetName) throws BiffException, IOException


{
Workbook workbook = Workbook.getWorkbook(new File(excelDataSheet));
Sheet sheet = workbook.getSheet(sheetName);
for (int i = 0; i < sheet.getRows(); i++)
{
Cell[] cell = sheet.getRow(i);
if (cell[0].getContents() != null)
{
TestParameterMap.put(cell[0].getContents().toString(), cell[1].getContents().toString());
}
}
}

Where -

excelDataSheet will be your excel file name with complete path

sheetName will be the sheet name in the excel file.

Usage

readExcelData(Complete Excel Path, Excel Sheet Name);

After this method is invoked the entire data from excel is stored in a HashMap. If we need to use a particular data we refer the
KeyName. To retrieve the key value we use this method.

public static String getValue(String key){


if (TestParameterMap.containsKey(key)){

return (String)TestParameterMap.get(key);
}
else{
return "Key not found";
}
}

For Eg

driver.navigate(getValue("KeyName"));

Sample excel data

How to switch between different windows using Selenium WebDriver

Inorder to switch between Windows we should be knowing the window handlers and traverse between windows.

For that i am opening the link in a new window using clicking down button, after that moving to the specified window.

Here is the code:


import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class MoveBetweenTabs


{
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver();
driver.navigate().to("http://www.google.com");

driver.manage().window().maximize();
WebElement oWE=driver.findElement(By.linkText("About Google"));

Actions oAction=new Actions(driver);


oAction.moveToElement(oWE);

oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perf
orm();

Set<String> sHandlers= driver.getWindowHandles();


for(String sHandler:sHandlers)
{

if(driver.switchTo().window(sHandler).getTitle().equals("Google"))
{
driver.switchTo().window(sHandler);
WebElement oWE1=driver.findElement(By.linkText("+Google"));
oWE1.click();
}
}
}

CSS Locator / CSS Selector Tutorial

CSS locating strategy is the fastest way to identify an element compared to any other locating strategy currently available.
Many of the automation frameworks now uses CSS as a locating strategy for locating elements. In this blog I will explain about
how to identify an element using CSS locators.

1. Locate an element using id.

<input id="textid" value="textid" type="text"/>


<button id="buttonid">Button wiht id</button>

Consider the above html code of a text box and a button, you can locate the above elements in html using there "id" attribute
value.
In CSS an element with id is identified by appending "#" to the start of its id attribute value. For ex the above text element can
be located as "#textid". Similarly the button element can be identified as "#buttonid"

2. Locate an element using class attribute.

<input class="textusingcls" value="Text with single class" type="text"/>


<button class="btnusingcls">Button with single Class</button>

Consider the above html code of a text box and a button, you can locate the above elements in html using there "class"
attribute value.
In CSS an element with class is identified by appending "." to the start of its class attribute value. For ex the above text element
can be located as ".textusingcls". Similarly the button element can be identified as ".btnusingcls"

Locating an element having more than one class, for ex. consider the following html code.

<input class="textcls1 textcls2" value="Text with multiple class" type="text"/>


<button class="buttoncls1 buttoncls2">Button with multiple Class</button>
The above element can be identified by replacing the spaces between the class values with "." . The above elements can be
located as ".textcls1.textcls2" and ".buttoncls1.buttoncls2" respectively.

3. Locate an element using html tag.

<input id="textid" value="textid" type="text"/>


<button id="buttonid">Button wiht id</button>

Consider the above html code of a text box and a button. To locate the above elements using there html tags in css, you just
have to use the tag name. For ex. The above two elements can be located as "input" and "button" respectively.

4. Locate an element using html tag, class, id all together.

<input id="textidcls" class="textidcls" value="Text with id and class" type="text"/>


<button id="buttonidcls" class="buttonidcls">Button with id and Class</button>

Consider the above html code of a text box and a button. You can locate the above element using a combination of html tag, id
and class all together. To do that just append all the three independent locator together. For the above element the unique
locators will be "input#textidcls.textidcls" and "button#buttonidcls.buttonidcls" respectively.

5. Locate element based on Parent element:

<input class="textcls" value="Text" type="text"/>


<button class="buttoncls">Button</button>
<div id="parent">
<div id="project-label">4. Locate Child element:</div>
<input class="textcls" value="Text" type="text"/>
<button class="buttoncls">Button</button>
<div>
<input class="textcls" value="Text" type="text"/>
<button class="buttoncls">Button</button>
</div>
</div>

Consider the above html code, if you try to find the text element using css locator ".textcls" you will get 3 elements in return. In
case you need to find the text box under the div element with id "parent" you can locate it using the locator "#parent .textcls",
but this also gives you 2 text box elements that are under the element with id "parent".
To find the direct child element of the "#parent" element you can use the ">" sign of css locator. So if you use the locator
"#parent > .textcls" it will give you the direct child of "parent" element.
In css if you use space between the parent and child element, it will return all the child elements under the said parent
irrespective of the hierarchy.

6. Identify an element using attribute value:

<input test="excttxt" value="Text for exact attr. value" type="text"/> </br>


<input test="strttxt1234" value="Text for starts with option" type="text"/> </br>
<input test="1234endtxt" value="Text for ends with option" type="text"/> </br>
<input test="12cntntxt34" value="Text for contains option" type="text"/> </br>

Consider the above html code, there are 4 text boxes each having a different value for attribute "test".Each element can be
uniquely identified by using the following strategies:

By exact attribute value: 'input[test="excttxt"] '


By using starts with: 'input[test^="strttxt"]'
By using ends with: 'input[test$="endtxt"]'
By using contains: 'input[test*="cntntxt"]'

I had created a dummy html page which can be download from the following link: CSS-Locator-demo
To use the demo for identifying a locator:
1. Unzip the downloaded zip and open the page "css_locator.html" in chrome or firefox.
2. Now go to console in the browser. For Chrome: Right Click -> Inspect Element -> Console. For Firefox: Right Click ->Inspect
with Firebug -> Console.
3. Use the jquery way of identifying element in the cosole. To do that type $('<Ur CSS locator>') under console and press enter.
Jquery will find the matching element for the said css locator and display it on the console as a link. If you hover on the said link
it will highlight the said element.
Here are the steps to get Firebug working in WebDriver based selenium testing-

1. Create a new firefox profile and install firebug in it.


1. launch profile manager- close all ff windows and type firefox -p into your run prompt.
2. Note where your profile is created. This will be needed in the java code for launching the ff with WebDriver.
3. Install firebug.
4. click on the firebug icon dropdown to select 'On for all web pages'.
2. Add the following code to your selenium tests-
File profileDir = new File("C:\\Users\\yourUserName\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\t8chq07l.selenium
testing");
FirefoxProfile profile= new FirefoxProfile(profileDir);
driver = new FirefoxDriver(profile);
Regular Expressions is a very powerful pattern matching tool. If you have used MSDOS or Bourne shell you are familiar with
wildcards like "*.txt" will match all files ending with .txt. Regular expressions take this to a whole new level.

First thing to note is there are different implementations of Regular Expression. The basic concepts are the same and most the
syntax is the same but there are subtle differences. I'll talk more about this as I give examples of the language.

The second thing to note is, some of the special symbols from MSDOS or Bourne shell are used by Regular Expression but they
have a completely different meaning. Most notably is the asterisk (*).

The example above, "*.txt", would be a bad Regular Expression. Why? The asterisk means the previous character zero or more
times. There is no character preceding the asterisk so it is a syntax error.

For simple things like "*.txt", Regular Expression can be overly complex. The dot (.) means any character. So if I want to emulate
the "*" of MSDOS, I would use ".*" in Regular Expression. If I wanted an actual dot I would use "\." in Regular Expression. So the
whole "*.txt" in MSDOS becomes ".*\.txt" in Regular Expression. In most languages, the "\." would get processes as a control
character by the String implementation. The slash (\) would never make it to the Regular Expression parser. So if you want "\."
to reach the Regular Expression parser, you need to use "\\." because the String implementation will parse this, resulting in "\.",
then pass it to the Regular Expression parser.

The language I use most right now is Java. If you look at the Java API documentation for the Pattern class you will see this is the
Regular Expression parser.

Some of the basic stuff:

Anything not a special character is matched verbatim. So in my example above "txt" only matches "txt".
If you want to match a special character you need to escape it. From my example, the dot is a special character. To match a dot
and nothing else you use "\\.". I use double slash because Java will parse the "\\" before sending it to Pattern.
Special characters from things like println() or printf() work the same in Regular Expression. These are "\t" for tab, "\n" for
newline, "\r" for return, "\f" for form-feed, "\a" for a bell. A bell in ASCII is control-g or "\x07" but "\a" is better because you
shouldn't assume ASCII.
You can have a sets using square brackets. If I have "[abc]" this will match "a", "b" or "c".
You can use the square brackets for negation. If the first character in the set is caret (^) it means 'not'. For example, "[^abc]"
would match anything not "a", not "b" and not "c".
If you want all digits you could use "[0123456789]" but there is a shorthand for this. A range can be specified using a minus (-)
symbol. This example would be "[0-9]". You can also do things like "[a-z]" but alphabetic strings can be problematic if you allow
different character sets.
If you want upper and lower case letters you might think "[a-Z]" would work but this is an error. The letter 'Z' in ASCII has a
value of 90 and 'a' has a value of 97. Second attempt might be "[A-z]". This is closer but in ASCII the symbols '[', '\', ']', '^', '_' and
'`' are between 'Z' and 'a'. So you have too many characters in this set. The solution is a union (like in Set Theory). You want "[a-
z]" union "[A-Z]". In Regular Expression this is written as "[a-zA-Z]".
You can also write a union as "[a-z[A-Z]]". This might seem like extra typing and in some cases it is. What if you wanted
all consonants? That would be 21 letters uppercase and 21 letters lower case. A string with 42 letters (you cannot really use a
single range). You could use "[b-df-hj-np-tv-zB-DF-HJ-NP-TV-Z]" but even that is a little ugly. How about: "[a-zA-
Z[^aeiouAEIOU]]". When I look at that it is pretty obvious what I'm trying to match. It reads as "all letters but not vowels".
There is 'syntactic sugar' for some things:
o Rather than "[0-9]" I can use "\d" (the d is for digit)
o Rather than "[^0-9]" I can use "\D" (uppercase implies NOT)
o Rather than "[ \t\n\x0b\\f\r]" I can use "\s" (the s is for space or whiteSpace)
o Rather than "[^ \t\n\x0b\\f\r]" I can use "\S" (uppercase implies NOT)
A 'word' is a String made of letters, digits or underscore. A character of a 'word' therefore would be: "[a-zA-Z\d_]". Syntactic
sugar for this is "\w".
Alternately, "\W" is for not a 'word' character.

Some slightly more advanced stuff would be boundary qualifiers:

The caret (^) not in a set means beginning of line. So if I have the string "^a" it matches if 'a' is the first character in the string.
With wildcards or substring matching this can be very helpful. For example, "^def" will not match a substring check with
"abcdefghi" but "def" will match.
The dollar ($) is for end of line. For example, "def$" will not match "abcdefghi" but "def" will match.
Capture groups are used for substitution. For example, if I have a string with my full name, "Darrell Grainger" and I want to
change it to "Grainger, Darrell" I would do the following:
String name = "Darrell Grainger";
String flip = name.replaceFirst("(\\w*) (\\w*)", "$2, $1");
The "\\w*" means get the first word. It will match "Darrell". By wrapping it with parenthesis it becomes a 'capture group'. So
the first "(\\w*)" gets saved into "$1" and the second "(\\w*)" gets saved into "$2". In other implementations of Regular
Expression, capture groups are saved into things like "\1" rather than "$1".
Capture groups are great if you are processing a number of strings in an array. This example will flip the first and second word
for any set of strings.
More advance stuff would be Greedy quantifiers versus Reluctant quantifiers. Lets look at this with capture groups.
String s = "aaabbbaaa";
String s1 = s.replaceFirst("(a*)(.*)", "$2 $1");
String s2 = s.replaceFirst("(a*?)(.*)", "$2 $1");
The string s1 will contain "bbbaaa aaa".
The string s2 will contain "aaabbbaaa ".

For s1, what happened is "(a*)" matched "aaa" and "(.*)" matched "bbbaaa".
For s2, what happened is "(a*?)" was a Reluctant quantifier. Because "(.*)" is a Greedy quantifier, it captured everything. This
left nothing for "(a*?)" to capture.

What happens under the hood is that the Regular Expression parser will find the Greedy quantifiers, read in the entire string
and see if it matches. If it does not it pushes one character back out, checks for a match, pushes a character back out, checks for
a match. It keeps doing this until it finds a match. Whatever didn't match is used to process Reluctant quantifiers.
While processing the Reluctant quantifiers the parser will read in one character, check for a match, read another character,
check for a match, read another character, check for a match. It keeps doing this so long as things are matching. The moment
there isn't a match it stops.

So the s1 string processed "(a*)" first, because it is a Greedy quantifier and captured "aaa" into "$1". Then it processed "(.*)"
which matched the rest of the string. This captured "bbbaaa" into "$2".

With the string s2 it processed "(.*)" because it is a Greedy quantifier and "(a*?)" is a Reluctant quantifier. The "(.*)" grabbed
the entire string and put it into "$2". This left an empty string "". The empty string is used to process the Reluctant quantifier
"(a*?)" and "" gets captured into "$1".

Here is a table of the Greedy versus Reluctant quantifiers:

Greedy Reluctant Meaning


X? X?? X, once or not at all
X* X*? X, zero or more times
X+ X+? X, one or more times
X{n} X{n}? X, exactly n times
X{n,} X{n,}? X, at least n times
X{n,m} X{n,m}? X, at least n but not more than m times

There is more the Regular Expressions but this information is what you need for most situations.

Dealing with web elements by different locators

Lets consider the following sample HTML code snippet as a reference point.

1. <!DOCTYPE HTML>
2. <html>
3. <head>
4. <script type="text/javascript">
5. function jsFunction(){
6. alert("Welcome to Selenium UI Automation Testing !");
7. }
8. </script>
9. </head>
10. <body>
11. <input type="submit" id="webButton" onclick="jsFunction()" value="Click It" />
12. <a href="http://aksahu.blogspot.in/">Go Home</a>
13. </body>
14. </html>

Lets start by taking example of any of the selenium command say "click"
You can use same fashion for any of the selenium command like i am using for click.
The click command emulates a click operation for a link, button, checkbox or radio button. It takes a locator (an identifier for
which HTML element the command refers to) as an argument.

Using Selectors with Click Command:


xpath

This allows clicking on an element using an XPath expression. Example

selenium.click("xpath=//input[@name=webButton' and @type='submit']");

css

CSS locator is used with Selenium commands to uniquely identify an object or element on a web page. Example,

selenium.click("css=input*name=webButton+);

name

The name selector is used to click the first element with the specified @name attribute. Example,

selenium.click("name=webButton);
or
selenium.click("webButton");

id

This allows click on an element with the specified @id attribute. Example,

selenium.click("id=webButton);

link

This allows clicking on a link element which contains text matching the specified pattern. Example,

selenium.click("link=Go Home);

Selenium Server problem: Failed to start: SocketListener0@0.0.0.0:4444

Sometimes after starting the server due to some problem test running browser get closed, in that case the started server(
linked with the browser) can't stop and shows errors like :
Failed to start: SocketListener0@0.0.0.0:4444

Solution for this problem:


Type the below in the browser URL and the server will be stopped.
http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer

Start and Stop Selenium Server Programatically

The Following code contains two methods.The first method startSeleniumServer() is for starting the server and the second
method stopSeleniumServer() is to stop the started server.With this we are also able to trace out the server log to a file
called "logs/seleniumServer.log" into your local machine.

1. protected RemoteControlConfiguration rc ;
2. protected SeleniumServer seleniumServer ;
3.
4. public void startSeleniumServer() {
5. try {
6. File logfile = new File("logs/seleniumServer.log");
7. rc = new RemoteControlConfiguration();
8. rc.setLogOutFile(logfile);
9. seleniumServer = new SeleniumServer(rc);
10. seleniumServer.start();
11. } catch (Exception e) {
12. e.printStackTrace();
13. }
14. }
15.
16. public void stopSeleniumServer() throws Exception {
17. seleniumServer.stop();
18. }

. SELENIUM WEBDRIVER WORKING

WebDriver is designed in a simpler and more concise programming interface along with addressing some limitations
in the Selenium-RC API.
WebDriver is a compact Object Oriented API when compared to Selenium1.0
WebDriver works at the OS/browser level:
For instance, command type works at the OS level rather than changing the value of the input elements with
JavaScript
It drives the browser much more effectively and over comes the limitations of Selenium 1.x which affected our
functional test coverage, like the file upload or download, pop-ups and dialogs barrier or self-signed certificates
problems

Selenium RC, It injects JavaScript functions into the browser when the browser was loaded and then used its JavaScript to
drive the AUT within the browser. WebDriver does not use this technique. Again, it drives the browser directly using the
browsers built in support for automation.

WebDriver drives the tests natively with the browser and emulates the Human interaction with website. Implementation differs
on each browsers.

The merge of the projects combines the strengths of both frameworks: Selenium 2.0 will provide both Selenium 1.x and
WebDriver APIs.

This document concentrates more on WebDriver implementation using the WebDriver Java API.
WebDriver is the name of the key interface against which tests should be written, but there are 11 implementing classes, listed
as below:

AndroidDriver,
AndroidWebDriver,
ChromeDriver,
EventFiringWebDriver,
FirefoxDriver,
HtmlUnitDriver,
InternetExplorerDriver,
IPhoneDriver,
IPhoneSimulatorDriver,
RemoteWebDriver,
SafariDriver
OOPs concept Class, Objects Polymorphism, Inheritance and Encapsulation
Java Programming essentials- Object Instances, method overloading/overriding concepts and packages
Control Statements While, do-While, Switch, If statements This will help us in writing the scripts for a multiple
scenario statements and decision making scenarios.
Looping statements This will help us in scenarios like, iterating through a large table to find a record that you want
and Running the same test for multiple number of times.
Arrays Concepts This will help us in having some set of datas of same type in a static way.
Threads and MultiThreading Concepts This will help us in making run our scripts in different threads that will help us
in achieving better performance.
Java Collections Framework ArrayLists and HashMaps This will help us in maitaining a collection of datas.
Particularly useful for scenarios where you need to compare the data from Web app UI with the DB. [OR] From UI to
another UI
File Streams This will be helpful in externalization of data through CSV, Excel or Java Properties file.

} Page Object Pattern, the term that selenium users keep buzzing. Page object is a design pattern that can be implemented as a
selenium best practices. The functionality classes (PageObjects) in this design represent a logical relationship between the
pages of the application.

The Page Object pattern represents the screens of your web app as a series of objects and encapsulates the features
represented by a page.
It allows us to model the UI in our tests.
A page object is an object-oriented class that serves as an interface to a page of your AUT.

More on Page Object Pattern at Selenium wiki. Some of the advantages of page object pattern as listed below,

Reduces the duplication of code


Makes tests more readable and robust
Improves the maintainability of tests, particularly when there is frequent change in the AUT. (Useful in Agile
methodology based projects)

Enough of theory, lets get into practical implementation.

Page Object, which models the Google search page:

[sourcecode language="java" wraplines="false" collapse="false"]


public class GoogleSearchPage {

protected WebDriver driver;


private WebElement q;
private WebElement btn;

public GoogleSearchPage(WebDriver driver) {


this.driver = driver;
}
public void open(String url) {
driver.get(url);
}
public void close() {
driver.quit();
}
public String getTitle() {
return driver.getTitle();
}
public void searchFor(String searchTerm) {
q.sendKeys(searchTerm);
btn.click();
}
public void typeSearchTerm(String searchTerm) {
q.sendKeys(searchTerm);
}
public void clickOnSearch() {
btn.click();
}
}
[/sourcecode]

WebDriver provides a way to map it to a real web page. The PageFactory class provides a convenient way of initializing and
mapping the Page Object fields.

[sourcecode language="java" wraplines="false" collapse="false"]


public class WhenAUserSearchesOnGoogle {

private GoogleSearchPage page;

@Before
public void openTheBrowser() {
page = PageFactory.initElements(new FirefoxDriver(), GoogleSearchPage.class);
page.open("http://google.co.in/");
}

@After
public void closeTheBrowser() {
page.close();
}

@Test
public void whenTheUserSearchesForSeleniumTheResultPageTitleShouldContainCats() {
page.searchFor("selenium");
assertThat(page.getTitle(), containsString("selenium") );
}
}
[/sourcecode]

By default, it will map Page Object properties to fields with matching ids or names, so the example given here will work fine out
of the box. But sometimes we need more control over identifying elements in the HTML page and mapping them to our Page
Object fields. One way to do this is to use the @FindBy annotation, as shown in the following code:

[sourcecode language="java" wraplines="false" collapse="false"]


public class GoogleSearchPage {

protected WebDriver driver;

@FindBy(name="q")
private WebElement searchField;

@FindBy(name="btnG")
private WebElement searchButton;
public AnnotatedGoogleSearchPage(WebDriver driver) {
this.driver = driver;
}

public void open(String url) {


driver.get(url);
}

public void close() {


driver.quit();
}

public String getTitle() {


return driver.getTitle();
}

public void searchFor(String searchTerm) {


searchField.sendKeys(searchTerm);
searchButton.click();
}

public void typeSearchTerm(String searchTerm) {


searchField.sendKeys(searchTerm);
}

public void clickOnSearch() {


searchButton.click();
}
}
[/sourcecode]

Selenium/ WebDriver Tips and Tricks

WebDriver

How to increase 45 sec waiting period to bind locking port 7054?

During parallel execution of tests on FireFox you may encounter this error

//unable to bind to locking port 7054 within 45 seconds


FirefoxBinary fb = new FirefoxBinary();
fb.setTimeout(java.util.concurrent.TimeUnit.SECONDS.toMillis(90));

WebDriver driver = new FirefoxDriver(fb, null); // or pass in a FirefoxProfile you want instead of the default webdriver creates.

Selenium RC
How to handle Selenium is already running on port 4444 ?

This is one of the common problems that we face while automate webapps using Selenium RC(Selenium 1.0).

Failed to start: SocketListener0@0.0.0.0:4444


Exception in thread "main" java.net.BindException: Selenium is already running on port 4444. Or some other service is.
at org.openqa.selenium.server.SeleniumServer.start(SeleniumServer.java:399)
at org.openqa.selenium.server.SeleniumServer.boot(SeleniumServer.java:234)
at org.openqa.selenium.server.SeleniumServer.main(SeleniumServer.java:198)

You can very well kill this session and start freshly by using the command below in the browser.
http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer

After you load this url the selenium sever that is running on port 4444 will be killed and you will notice a OKOK message in
the browser.

How to start Selenium Server Automatically using Java code ?

Starting selenium sever manually in a Terminal(mac) or command prompt (windows) is a must do task before you kickoff
your tests and we some times forget to do that and feel embarrassed (mainly in demos )

This is method of automatically starting and shutting down of selenium server through Java code comes handy when the
selenium RC scripts needs to be integrated with CI like Jenkins or Travis.

Starting selenium server


public static void startSeleniumServer(SeleniumServer server) throws Exception {

try {
ServerSocket serverSocket = new ServerSocket(RemoteControlConfiguration.DEFAULT_PORT);
serverSocket.close();

try {
RemoteControlConfiguration rcc = new RemoteControlConfiguration();
rcc.setPort(RemoteControlConfiguration.DEFAULT_PORT);
server = new SeleniumServer(false, rcc);

} catch (Exception e) {
System.err.println("Could not create Selenium Server because of: "
+ e.getMessage());
e.printStackTrace();
}
try {
server.start();
System.out.println("Server started");
} catch (Exception e) {
System.err.println("Could not start Selenium Server because of: "
+ e.getMessage());
e.printStackTrace();
}
} catch (BindException e) {
System.out.println("Selenium server already up, will reuse...");
}
}
Stopping Selenium Server
public static void stopSeleniumServer(SeleniumServer server, DefaultSelenium selenium){
selenium.stop();
if (server != null)
{
try
{
selenium.shutDownSeleniumServer();
server.stop();

server = null;
}
catch (Exception e)
{
e.printStackTrace();
}
}

1. Which is the only browser in which Selenium IDE can be used ?


A)Safari B)Firefox C)GoogleChrome D)Internet Explorer

Answer: Firefox

2. Selenium supports which kinds of applications?


A) Web Based applications B)Stand alone applications C)Both D)None of the above

Answer: Web Based Applications

3. Find the type of text pattern used in Selenium


A) Chronological Sequence B) Globbing C) Simulation D)None of the above

Answer: Globbing

Will be updated with more questions then and there. Keep visiting

Selenium RC

1. Which of the following command is a Onevent Handler


A) focus() B) assertAlert() C) fireEvent() D) alert()

Answer: fireEvent()

2. Selenium server is developed in


A)Perl B) Java C) Python D).Net

Answer: Java

Will be updated with more questions then and there. Keep visiting
Selenium WebDriver

1. Which Driver implementation will allow headless mode


A) FireFoxDriver() B) HtmlUnitDriver() C)SafariDriver D) ChromeDriver

Answer : HTMLUnitDriver

iFrames

An inline frame is used to embed another document within the current HTML document. It means iframe is actually a webpage
within the webpage which have its own DOM for every iframe on the page.

the HTML source code of the webpage that has an iframe will look like the below code.
In the above html snapshot there is an iframe embed into an another iframe. And We have to select the outer Iframe to go to
inner Iframe and write in the body.

Next We have to come out from the inner iframe to outer iframe and click on OK button

Directly accessing the above elements is not possibe iframes has its own DOM elements and we have to switch to that
particular frame and then perform any actions.

Selects the frame 1

driver.switchTo().frame("frame1");

Selects the frame2

driver.switchTo().frame("frame2");

Switching back to the parent window

driver.switchTo().defaultContent(); // you are now outside both frames

There might be situations like, we might not be able to get the iframe values. At that time we can get name by using tagName
method.

driver.switchTo().frame(driver.findElements(By.tagName("iframe").get(0));
So, you can actually select an iFrame using the below metthods,

frame(index)
frame(Name of Frame [or] Id of the frame
frame(WebElement frameElement)
defaultContent()

Lets have a look at this iframes in the w3schools web page to learn interactively
So, you can tryhere

In the above image if you look at the html source we have 2 iframes defined
In the Firebug source code, you will see 3 frames shown
1.

iframe id="viewIFRAME";

2.

iframe src = "http://www.w3schools.com">

3.

iframe src="http://www.assertselenium.com"

It shows 3 iframes though we have defined only 2 because, the right hand viewer side itself is a made up of frame and inside
which we have 2 iframes defined.
If you look, while mouse hovering on

iframe id="viewIFRAME";

the whole right hand side area is highlighted, which shows that its an iframe.

If you look, while mouse hovering on

iframe src = "http://www.w3schools.com";


the w3schools iframe is highlighted

If you look, while mouse hovering on

iframe src = "http://www.assertselenium.com";


the assertselenium iframe is highlighted

Suppose if you view the same page in a 3D view you can actually see that these 3 iframes itself will be of separate individual
boxes, representing that its a iframe and has its own DOM

A special, In 3d View for you


So,thats pretty much about iFrames and I hope it helps you..!!!

Selenium Remote control got birth from the JavaScriptTestRunner that Jason huggins developed for automating their In-House
Time -n- Expenses application.

Selenium RC had few limitations that created serious problems with the advancement of rich internet applications like Same
Origin Policy file Uploads and few others..

Selenium RC is officially deprecated now with no further development but with a maintenance mode and its high time that we
need to migrate to WebDriver.

Over these past years, we have spent many time in developing automated web tests with selenium RC and its not possible to
migrate Selenium RC Scripts to WebDriver overnight, but a high amount of time and cost involves in migrating scripts to
WebDriver.

If you are starting fresh, then it should be WebDriver.

Using WebDriverBackedSelenium makes sense to easily migrate your test scripts from Selenium Rc to WebDriver.

Lets see how we migrate from Selenium RC to WebDriver

Selenium RC code look like this

String strBaseUrl = "http://assertselenium.com/";


String strBrowserName = "*firefox"
String strPortNumber = "5555"
String strHost = "localhost"
selenium = new DefaultSelenium(strHost, strPortNumber , strBrowserName , strBaseUrl);
selenium.start();
selenium.open("/");
selenium.click("link=Contact Me");
selenium.waitForPageToLoad("30000");

//Can be many more steps involved...

selenium.stop();

You may use any WebDriver implementation, here we use Firefox Driver

String strBaseUrl = "http://assertselenium.com";

//Creating a WebDriver implementation


WebDriver driver = new FirefoxDriver();

//Selenium rc implementation
Selenium selenium = new DefaultSelenium(driver, strBaseurl);

//Performing actions with selenium


selenium.open("/");
selenium.click("link=Contact Me");
selenium.waitForPageToLoad("30000");

//Can be many more steps

/* And get the underlying WebDriver implementation back.


*This will refer to the same WebDriver instance as the "driver" variable above.
*/
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getUnderlyingWebDriver();

Using selenium.start() is not required because, we have already created the WebDriver session. At the end of the test we
shall use the driver.quit() instead of selenium.stop().

WebDriver doesnt support all browsers as Selenium Rc used to support. In order to use that ability while still using the
WebDriver you shall use the SeleneseCommandExecutor

It can be done using,

Capabilities dCaps = new DesiredCapabilities()


dCaps.setBrowserName("some new browser");
CommandExecutor executor = new SeleneseCommandExecutor("http:localhost:4444/", "http://www.google.com/",
capabilities);
WebDriver driver = new RemoteWebDriver(executor, dCaps);

Selenium RC to Webdriver Migration Part1

I have been using Selenium RC successfully to implement automation from the past couple of years in most of my projects and
did not face major issues. I had used Selenium RC in our projects to the full extent that it supports. Selenium like any other tools
has its own advantages and limitations. Most of the limitations have been overcome by integrating some third party API or
some kind of work around.
The way Selenium RC automates a web application is that, it injects JavaScript into the web application. Typically websites
coded heavily in Java scripts and with this additional Java script injection are likely to cause application performance issues
during Automation. Also Selenium RC does not simulate the actual user interactions on the browser which poses some
limitation with certain actions on few web applications.

Some of the limitations that selenium RC pose are while landing into a page whose domain are different from the actual page
where the selenium RC has started, permission denied errors are displayed. This is because of the same origin policy. However
this is not the case all the time as Selenium itself acts as a proxy to the actual site.

Also using Selenium RC, I was able to handle the SSL Certificate warning page issues. Every time selenium starts; it creates new
custom Firefox profiles and new instances of Internet Explorer.

I followed the below approaches to handle the SSL Certificate errors on different browsers using Selenium RC:

Create custom Firefox profile import the certificate manually and then use the same profile to automate the test
For Internet Explorer, installed cyber villain certificate and then start server setting the flag TrustAllSSLCertificates.

With the above approach, I was able to automate the SSL web application on both Firefox and Internet Explorer. However at
times, I encountered the permission denied errors like when I trigger some click event which launches a different domain
website. Also, installing cyber villain certificate did not solve the issue of certificates page for some untrusted SSL certificate
sites and self-Signed certificate sites.

Selenium 2.0 versions, which is a combination of both Selenium RC and Webdriver claim to solve the SSL issues and also it does
the actual user simulation by directly interacting with the browser . With this, it removes the overhead of JavaScript injections
in to the browsers. Since the initial development of the Webdriver releases (Selenium 2.0a1)has multiple versions of build
releases, I was keenly waiting for a stable release so that I could easily migrate to Webdriver and start using it on current
projects.

The actual beauty of Selenium is that, it allows user to switch their instance from Webdriver to Selenium and back from
Selenium to Webdriver thereby supporting the backward compatibility of exiting scripts. Also Selenium Webdriver version
supports some the advanced user keyboard and mouse actions using Native Events. And slowly the support to Selenium RC
versions has been stopped.
In one of the recent projects, I had faced an issue with the Internet Explorer when Selenium RC shows up a certificate error
page The website you are trying to access is not trusted. This is one of the blocker for our current requirement. I tried
installing cyber villain certificate but still the issue persists. However, I try to open in it manually; I dont see the certificate
error. And most of the time this behavior is inconsistent. Reason is that manually, if you install the certificate, the certificate get
installed in the default instance of Internet explorer and when the tests are run using Selenium RC, a new instance of the
Internet Explorer is created and the certificate installed previously does not gets stored in new instance

After going through many forums and based on the advanced features that webdriver supports, I decided to go over Webdriver
release but I was a bit concerned over the migration, as it requires a huge effort migrating from Selection RC to WebDriversince
the API exposed by Selenium RC is different from Webdriver API.

Here are the approaches that I had in my mind for a gradual migration:

Use SeleniumWebdriver backward compatibility Webdriver Backed Seleniumwhich would require a minimal effort
in migrating to Selenium Webdriver version with minimal code changes and chances of impact on the automation
scripts rework are less as WebdriverBackedSelenium uses the same command as Selenium RC supports.
Once the scripts are stable with the above approach, do a complete migration to webdriver API to get rid of selenium
commands that uses Java Script injection and permission denied errors

First thing I had in my mind is to verify all the issues that we had encountered in the past are resolved or not . I downloaded the
Selenium Webdriver 2.18 version which was the latest version at that moment and started creating a command compatibility
matrix and then followed as below.

1. Configured Sample Java Project with the Selenium Jars


2. Created a sample script that opens up the Internet explorer

Once it was confirmed that most issues are resolved using Web Driver, I started working on the detailed migration and plan.
First activity as part of the migration plan was to create a Selenium RC vs Web Driver command compatibility matrix to help us
create the plan for migration.

As a first step, we migrated the scripts to use Selenium backed WebDriver. During this effort, following were key things that had
to be included in the WebDriver initialization code.

Firefox Driver

Support for setting up command line switches (refer to http://code.google.com/p/selenium/wiki/FirefoxDriver for


more details).
Support for firefox custom profile
Support to handle untrusted certificates and issuers

Internet Explorer Driver

Support for SSL certificates

Google Chrome Driver


Support for setting up command switches (refer to http://code.google.com/p/selenium/wiki/ChromeDriver for more
details)

Selenium RC to Webdriver Migration Part2

Listed below are the issues I had encountered and how I was able to overcome during the Webbriver migration

Internet explorer issue during web driver start up

When I first ran the Webdriver tests against Internet Explorer, I got the error Unexpected error launching Internet Explorer.
Protected Mode must be set to the same value (enabled or disabled) for all zones. The work around for this issue is to either
manually set the entire protected mode to enabled/disabled from the security tab

Another alternative to avoid the above IE settings is to use the below snippet

SSL Certificate Issue:

As next steps, I tried to check the SSL support and ran a sample test against HTTPS site. I could see the same issue what I had
seen in the past and it was a big disappointment for me.

1. I read in forums, that webdriver opens the default internet explorer instance. I started thinking that, if I could install
the certificate, then the certificate would be stored in internet explorer and the same instance would be used by
Webdriver.
2. Then I opened the Internet Explorer manually and tried to install the certificate and to my utter shock, I did not find
any options to install the certificate and later I came to know that we need to have admin privileges to install the
certificate on my machine. Got help from my IT team to install and configure the certificate.
3. I again restarted the browser manually and opened the same SSL URL. Surprisingly this time there is no certificate
page displayed.
4. I ran the script with Webdriver and could still see the Certificate alert The content you are trying to view is not
secure. I had tweaked the code as below with which finally I was able to get rid of the certificates

For Internet Explorer


For Firefox

Create a custom Firefox profile and then import the certificate and add the below code to load the custom profile

WebdriverElement not found issue (Element poll time)

I was able to migrate the webdriver implementation into our framework and just ran some of set of tests and to my surprise
most of the tests failed with the reason Element Not Found Exception. Also most of the teams who were using the webdriver
implementation started complaining that webdriver execution is very fast and that it doesnt even wait for the element to
appear on the screen. I searched many forums on how to control the speed of the execution but not luck that webdriver does
not support controlling the speed of the execution. After some analysis I had found that, the way webdriver tries to identify the
elements is by polling the HTML DOM and checks for existence of element in the HTML DOM. Further , I found that the
application which Im using tends to construct the DOM slowly which is why Im getting Element Not Found Exception.
Whenever the tests are executed webdriver simply checks if the element is present in the DOM. If the element is present, it will
perform else throws Element Not Found Exception. Finally, I found that there is a way we can provide poll time as a
configurable parameter to webdriver to poll the DOM with some time out polling condition provided and this poll time needs to
be set once the driver is instantiated. Here is the code I had added to control Webdriver polling time for a timeout of 10
seconds and it worked like a charm.

Multiple window issues

There are couples of scenarios where I need to switch to a new browser window and perform actions on the new window.
Selenium supports switching between multiple windows using browser titles/window id. The actual issue I had faced was that
the browser had the title but title was dynamically generated and new browser did not even have a window id/name to handle.
However, we have done some work around with Selenium RC to handle the new browser window With the Webdriver, I was
able achieve switching between multiple windows in a much easier way . Webdriver would return all the open window handle
ids as a set. We can use 0 to select Parent Window and 1 for child window. Likewise for subsequent child windows we can

increment the Handles and select them.

selenium RC to Webdriver Migration Part3

Wait For Popup Issue.

Using selenium RC, it was simple to handle synchronization time for window browsers using waitForPopup command which
allows us to pass the window id as a parameter to that command. Actual problem occurs when the popup does not have any
window id. With webdriver there is not such waitForPopup command. I had created the sample utility to achieve the popup
synchronization time.You need to pass the window index to wait for a particular window. Ex: If you have two windows, for
selecting second window you will need to pass 1 . To switch to the first window you need to pass 0 .Here the index of the
handles start from 0.
Opening new browser window workaround with webdriver.

Like Selenium RC, Webdriver does not provide a direct command to open a new instance of browser. Instead we need to use
Webdriver JavaScript executor to open up a new window .Here is the code snippet that I had used to open a new browser with
some desired url, wait until new browser is loaded with url and then select the new browser.Here we need to pass URL as a
parameter
Im going to post few more Interesting issues and workarounds (refer below) in my upcoming blogs.

Google Chrome Browser died issue


Google Chrome command switches
Mouse over issue and its limitation with current Firefox versions(native events) and Internet explorer
WebdriverBackedSelenium command issues.
Java Script Alert and confirmation issue.
Webdriver Type Command issue
Seleniums IsElementPresent command issue in Webdriver
Browser Native Events Implementation
JavaScript execution
Highlight an element with custom color formats
Element synchronization time
Switching Frame issues
JUNIT JAVA FRAMEWORK

What is JUnit?

JUnit is the unit testing Java framework use for writing repeatable tests. When uses with Selenium, helps integrating various
modules implemented under any automation framework For Exmaple, we have a code which reads the xls file, 2nd code that
creates the database connectivity, 3rd code that generates the HTML reports and 4th code that generates some logs and there
are other Java files written for performing various operations like database handling, generating test results etc.

Now we have a controller placed in between these codes which will maintain the flow of execution i.e. a framework JUnit or
TestNG If we want to run all these scripts in single execution then we need a controller which will going to handle all these
executions sequentially using differnt JUnit annotations.

Training will be provided on both TestNG and JUnit Java framework since there are some companies that are using JUnit and
some are on TestNG.

What makes it different from Selenium RC?

More object oriented as compare to Selenium RC.


Has wider range of APIs
Interacts natively with browser where as Selenium RC is Javascript based.
Can test Iphone and Andriod based application which is not supported by Selenium RC.
Implements HTMLUnit driver which makes test execution really fast.
Unlike Selenium RC there is no server in Webdriver.
Supports almost all lastest web browsers where as Selenium RC does not works on latest versions on Firefox and IE.

Selenium is a Automation tool for testing WebApplications. And using this we can automate ONLY web applications but not
Windows based applications.

Install Selenium IDE and start playing with it. It is one of the simple tool which doesn't require much detailed explanations :)

But Selenium IDE itself is not enough for effective test script as it doesnt supports looping(for, while etc..) and our cusom
needs.So we need to use other programming languages to customize testscript and achieve what our test senario demands.

Executing javascript using Selenium WebDriver

Using webdriver sometimes we need to run javascript code dircetly from our script.

In one of the previous post we have discussed how to break catcha on webpage . To break captcha we need to run javascript
code directly from our script .So it is important to know how to run javacript code using WebDriver. Here are the steps:

1.Cast the WebDrier instance to a JavascriptExecutor

view plainprint?

1. WebDriver driver;
2. JavascriptExecutor js = (JavascriptExecutor) driver;

2.Use executeScript method to run the script


view plainprint?
1. js.executeScript("return document.title");

Here is the sample script using TestNG.


view plainprint?

1. import java.util.ArrayList;
2. import org.openqa.selenium.JavascriptExecutor;
3. import org.openqa.selenium.WebDriver;
4. import org.openqa.selenium.firefox.FirefoxDriver;
5. import org.testng.Reporter;
6. import org.testng.annotations.AfterTest;
7. import org.testng.annotations.BeforeTest;
8. import org.testng.annotations.Test;
9.
10. public class ExecuteJavascript {
11.
12. WebDriver driver;
13.
14. @BeforeTest
15. public void start(){
16. driver = new FirefoxDriver();
17. }
18.
19. @Test
20. public void javaScriptExec(){
21.
22. driver.get("http://duckduckgo.com/");
23. JavascriptExecutor js=(JavascriptExecutor) driver;
24.
25. String readyState=(String)js.executeScript("return document.readyState");
26. System.out.println("readyState : "+readyState);
27.
28. String title=(String)js.executeScript("return document.title");
29. System.out.println("title : "+title);
30.
31. String domain=(String)js.executeScript("return document.domain");
32. System.out.println("domain : "+domain);
33.
34.
35. String lastModified=(String)js.executeScript("return document.lastModified");
36. System.out.println("lastModified : "+lastModified);
37.
38. String URL=(String)js.executeScript("return document.URL");
39. System.out.println("Full URL : "+URL);
40.
41. String error=(String) ((JavascriptExecutor) driver).executeScript("return window.jsErrors");
42. System.out.println("Windows js errors : "+error);
43.
44. }
45.
46. @AfterTest
47. public void stop(){
48. driver.quit();
49. }
50.
51. }
Selecting a date from Datepicker using Selenium WebDriver

Calendars look pretty and of course they are fancy too.So now a days most of the websites are using advanced jQuery
Datepickers instead of displaying individual dropdowns for month,day,year. :P

If we look at the Datepicker, it is just a like a table with set of rows and columns.To select a date ,we just have to navigate to the
cell where our desired date is present.

Here is a sample code on how to pick a 13th date from the next month.

view plainprint?

1. import java.util.List;
2. import java.util.concurrent.TimeUnit;
3. import org.openqa.selenium.By;
4. import org.openqa.selenium.WebDriver;
5. import org.openqa.selenium.WebElement;
6. import org.openqa.selenium.firefox.FirefoxDriver;
7. import org.testng.annotations.BeforeTest;
8. import org.testng.annotations.Test;
9.
10. public class DatePicker {
11.
12. WebDriver driver;
13.
14. @BeforeTest
15. public void start(){
16. System.setProperty("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
17. driver = new FirefoxDriver();
18. }
19.
20. @Test
21. public void Test(){
22.
23. driver.get("http://jqueryui.com/datepicker/");
24. driver.switchTo().frame(0);
25. driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
26. //Click on textbox so that datepicker will come
27. driver.findElement(By.id("datepicker")).click();
28.
29. //Click on next so that we will be in next month
30. driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();
31.
32. /*DatePicker is a table.So navigate to each cell
33. * If a particular cell matches value 13 then select it
34. */
35. WebElement dateWidget = driver.findElement(By.id("ui-datepicker-div"));
36. List<webelement> rows=dateWidget.findElements(By.tagName("tr"));
37. List<webelement> columns=dateWidget.findElements(By.tagName("td"));
38.
39. for (WebElement cell: columns){
40. //Select 13th Date
41. if (cell.getText().equals("13")){
42. cell.findElement(By.linkText("13")).click();
43. break;
44. }
45. }
46. }
47. }</webelement></webelement>

You might also like:

Вам также может понравиться