Professional Documents
Culture Documents
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.
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:
3. EXCEPTION TEST
//TestNG
@Test(expectedExceptions = ArithmeticException.class)
4. Ignore Test
//JUnit
//TestNG
@Test(enabled=false)
public void IgnoreTest() {
System.out.println("Method is not ready yet");
}
5. SUITE TEST
5. Suite Test
@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.
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
@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
//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.
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
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 IDE
- Firefox add-on
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;
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.
* String
* Number
* Boolean
* Node-set
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]");
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')].
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.
import org.testng.annotations.*;
/**
*/
@Test
@Test(dependsOnMethods={"method1"})
}
Result
PASSED: method1
PASSED: method2
The method2() will execute only if method1() is run successfully, else method2() will skip.
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");
}
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.
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 *
*
*/
@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.
TestNG Grouping is highly flexible and useful, especially when you implement it in your project integration testing.
Interview Questions
-Interview Ques: How to extract data from webtable or weblist, store it in a file and sort the file
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.*;
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....
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
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.
rank.put(1,"A");
rank.put(1,"B");
rank.put(1,"C");
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);
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.
str.add ("Apple");
str.add ("Boy");
str.add ("Cat");
if (str.contains("Apple"))
Interface Implementation:
Implementations
Interface Array Balanced Tree Linked List Hash table
List ArrayList LinkedList
Map TreeMap HashMap
Set TreeSet HashSet
Deque ArrayDeque LinkedList
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:
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
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
// String Operations
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
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.
Example:
package com.oops;
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.
Example
package com.oops;
class OverExample{
}
public class OverRiddingExample extends OverExample{
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.
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 class SingleInheritence extends TwoWheeler {
Output
=======
true
Calling method in SuperClass
Color: Red & Brand:Own
Below example contains Single Inheritance and Multiple Inheritance Using Interfaces.
package com.oops;
class TwoWheeler{
int count=1;
interface Car
{
public void setBrandname(String name);
}
interface HeaveyVechile{
@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.
interface 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");
statements
}
Encapsulation in Java Programming
EmpDetails.java:
package com.oops;
EncapsulationExample.java
package com.oops;
/**
* @param args
*/
public static void main(String[] args) {
EmpDetails emp1=new EmpDetails();
emp1.setEmpid(1);
emp1.setEmpName("First");
Output
==========
Employee details id: 1 and name:First
Java Exception Handling Programming Questions
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.
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.
try {
} catch (Exception e) {
}finally{
Example
======
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) 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.
int a;
public NullException(int i) {
i=a;
}
int k=a/b;
throw new NullException(k);
}
public static void main(String args[]){
try{
}
}
Output
=========
Main CustomExceptionm:Created NullException:0
Finally Exceuting
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.
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;
}
}
int arr[]={1,4,5};
Output
============
arr Element1
arr Element4
arr Element5
Failed on exception3
Catch Retrun
Finally ReturnThread Example in Java
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;
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
int a[]={1,2,46,672,24,5,6,46,672};
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;
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
Assertion Statements:
1. Assert command will fail and abort current execution
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.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
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 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 }
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;
suite.addTestSuite( TestCase1.class);
suite.addTestSuite( TestCase2.class);
suite.addTestSuite( TestCase3.class);
return suite;
}
}
}
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 testgoogling() {
selenium.open("/");
selenium.type("q", "Niraj");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Niraj"));
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 {
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.
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.
<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.
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.
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.
After you finish the test, it's a good practice to kill the WebDriver instance using the quit() method, as shown in Listing 5.
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.
webdriver.get(https://github.com);
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
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.
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.
<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.
<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.
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()).
At this point, you can make the first assertion on the number of items retrieved, as shown in Listing 14.
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.
In a similar fashion, you can collect all five anchors, as shown in Listing 16.
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.
@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());
// 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.
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.
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.
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.
After registering a few browsers, the Selenium Grid 2 console should look like Figure 2.
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.
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.
@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);
Assert.assertEquals(5, lis.intValue());
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.
5
(3 votes)
driver.switchTo().frame("frame")
As well as by index:
driver.switchTo().frame(0);
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.
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.
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;
@Test
driver.get("http://www.google.com");
screen.wait(image, 10);
screen.click(image);
import org.junit.Test;
import org.sikuli.script.App;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
screen.wait(image, 10);
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;
@BeforeClass(alwaysRun = true)
protected void startWebDriver() {
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 120);
}
@AfterClass(alwaysRun = true)
protected void closeSession() {
driver.close();
}
}
VisibilityOfElementLocated.java
package tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
By findCondition;
VisibilityOfElementLocated(By by) {
this.findCondition = by;
}
import org.openqa.selenium.By;
import org.testng.annotations.Test;
//variables
public static final String YAHOO_EMAIL = "example@yahoo.co.uk";
public static final String HOTMAIL_EMAIL = "example@hotmail.co.uk";
//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();
//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();
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();
}
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:
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.
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()
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.
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
//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 = "']";
try {
while ((driver.findElement(By.xpath("//*[@id='pageNext']"))) != null) {
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();
}
1. Click a RadioButton:
var radioButton = driver.FindElements(By.Name("colorname"))[0];
radioButton.Click();
3. Check Checkbox:
var checkBox = driver.FindElement(By.Id("checkboxId"));
checkBox.Click();
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..
1. IDE
2. Selenium Jars
IDE: It is a tool that enables the programmer to write coding and organizing the code in a simplified manner.
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:
7. After downloading the Software go to the folder where download has done and click on the icon "eclipse.exe"
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
Once the IDE has been configured successfully: Do the following steps to configure selenium selenium in your eclipse IDE:
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.
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.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
OOP's Concepts
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.
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 :
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
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);
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
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();
cap.setCapability(CapabilityType.BROWSER_NAME, "firefox");
cap.setCapability(CapabilityType.PROXY, proxy);
FirefoxDriver driver= newFirefoxDriver(cap);
driver.get("http://www.google.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");
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.
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.
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.
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
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();
java.util.Iterator<String> it = winIds.iterator();
//System.out.println(it.next());
driver.findElement(By.xpath("//*[@id='lnkCountryLookupAIR_CC']")).click();
winIds = driver.getWindowHandles();
it = winIds.iterator();
//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
Three windows are open. Now I want to active second window and display second window name.
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()
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;
@Test (dataProvider="getData")
public void bookReturn(String depart, String arrive, String d,String adultpax,String childpax) throws InterruptedException,
ParseException{
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();
selectMonth(travelMonth);
selectDay(day);
driver.findElement(By.xpath("//*[@id='bookingModule-submit']")).click();
String part1="//*[@id='ui-datepicker-div']/div[1]/table/tbody/tr[";
String part2="]/td[";
String part3="]";
@DataProvider
public Object [][] getData(){
//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;
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);
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.
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,
example:
xpath:
//*[@id="ctl00_ctl25_g_669e9a2c_9c06_418f_8691_f172262a5de6_ctl01_txtUserName"]
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
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 ...
!!!!
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;
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);
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();
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?.
myProfile.setPreference("capability.policy.default.Window.frameElement.get","allAccess");
myTestDriver.manage().window().maximize();
myTestDriver.get("http://tinyurl.com/cb3lbho");
Thread.sleep(5000L);
try {
System.out.println(AlliFrameID.size());
for(int i=0;i<=AlliFrameID.size();i++){
} catch (Exception e) {
i come across with following interview question.Any one with answers please reply....
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.
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
System.out.println("Price is --->"+FirstItemPrice);
driver.get("http://www.amazon.co.uk");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id='twotabsearchtextbox']")).sendKeys("Ipad");
driver.findElement(By.xpath("//*[@id='nav-bar-inner']/div/form/div[2]/input")).click();
Assert.assertEquals(Temp[6], "Results");
System.out.println("Price is --->"+FirstItemPrice);
Thanks
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.
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
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();
// 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);
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);
//After finished your operation in pop-up just select the main window again
driver.switchTo().window(mwh);
while(windowIterator.hasNext()) {
String windowHandle = windowIterator.next();
popup = browser.switchTo().window(windowHandle);
if (popup.getTitle().equals("Google") {
break;
popup.findElement(By.name("q")).sendKeys("Thoughtworks");
popup.findElement(By.name("btnG")).submit();"
3) After the popup actions, switch the driver back to the parent window,
driver.switchTo().Frame(driver.findelement(by.id("iframeid")));
// perform ur actions.
//revert back to parent control
driver.switchTo().window(parentWindowHandle);
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.
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()
deselectByIndex(int index)
deselectByValue(java.lang.String value)
deselectByVisibleText(java.lang.String text)
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
}
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)
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");
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
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>
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");
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
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 {
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();
}
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;
}
}
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)
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?
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();
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:
view plainprint?
1. driver.findElement(By.id("textBoxId")).sendKeys("sending text");
1. driver.findElement(By.id("radioButtonId")).click();
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();
1. driver.findElement(By.id("dropdownListId")).sendKeys("SelectOption1");
1. driver.findElement(By.id("textAreaId")).click();
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. }
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
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.
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?
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
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();
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:
view plainprint?
1. driver.findElement(By.id("textBoxId")).sendKeys("sending text");
1. driver.findElement(By.id("radioButtonId")).click();
1. driver.findElement(By.id("linkId")).click();
1. driver.findElement(By.id("checkBoxId")).click();
1. driver.findElement(By.id("dropdownListId")).sendKeys("SelectOption1");
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. }
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:
I have a selenium RC code below which selects list of drop down values and stores in array
would suggest to you use List instead of String to store the values. You could use WebDriver to achieve this as following -
WebElement element=driver.findElement(By.id("allpage_links"));
List<WebElement> rowCollection=element.findElements(By.xpath("//*[@id='allpage_links']/tbody/tr"));
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+"]";
Let us list some of the actions that we need to automate while automating a test case:
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)
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.
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.
call the static method wherever necessary selectValue(Texas) will select the value Texas from the dropdown country.
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()
Above code snippet will first click the checkbox named kannada and then verifies whether it is clicked or not.
Follow the same steps which are used in Checkbox to select a radio button and then verify the status using isSelected() method.
Afghanistan
Albania
India
China
Here,
// String Operations
OutPut:
========
String1 == String3true
String2 at Index 2:
Substring of String1l
Convert to LowerCaseja va
if (n == rev) {
return true;
} else {
return false;
}
}/** Number palindrome */
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
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.
Example:
package com.oops;
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 class OverRiddingExample extends OverExample{
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;
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name");
boolean exist=fname.createNewFile();
System.out.println("Successfully created");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
========
Successfully created
package com.io;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
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,
Thanks
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.
rank.put(1,"A");
rank.put(1,"B");
rank.put(1,"C");
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);
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.
str.add ("Apple");
str.add ("Boy");
str.add ("Cat");
if (str.contains("Apple"))
Interface Implementation:
Implementations
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"));
}*/
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.
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;
Advantages of WebDriver
Advantages of web driver
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"):
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:
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".
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.
3) After the popup actions, switch the driver back to the parent window,
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".
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.
3) After the popup actions, switch the driver back to the parent window,
File scrFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\Local Disk D_9220122129\\tmp.jpg"));
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("Button")) {
if (selenium
.isElementPresent(s.getCell(0, i).getContents())) {
selenium.click(s.getCell(0, i).getContents());
}
}
}
}
return "pass";
}
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;
}
}
-----------
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;
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() ;
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.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 :
Keyword driven framework is an action based test method used in planing and implementation of automation.
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".
import com.thoughtworks.selenium.DefaultSelenium;
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("");
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.
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);
@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
<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>
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.*;
@DataProvider(name="DP1")
public Object[][] createData(){
Object[][] retObjArr = {{"testuserA","password1"},
{"testuserB","password2"},
{"testuserC","password3"},
{"testuserD","password4"},
{"testuserE","password5"},
};
return(retObjArr);
}
@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();
}
}
@AfterTest
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumServer.stop();
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.*;
@BeforeClass
public void setUp()throws Exception{
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$]" );
while (rs.next()) {
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());
}
}
}
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 {
@Test
@Parameters( {"BROWSER"})
public void testread(String BROWSER)throws Exception{
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);
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
try{
p.load(new FileInputStream("propertyname.properties");
}
catch(Exception e ){
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
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:
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)
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.
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.
if (valToBeSelected.equalsIgnoreCase(option.getText())){
option.click();
call the static method wherever necessary selectValue(Texas) will select the value Texas from the dropdown country.
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()
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.
Follow the same steps which are used in Checkbox to select a radio button and then verify the status using isSelected() method.
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);
fd.findElement(By.xpath("//select[@id='from1Select']/option[@value='Goa'"]")).click();
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.
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.
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;
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;
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
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();
}
}
INDEX
Steps to implement Browser back and forward through Selenium Web Driver
2. Go to the URL
CODE: driver.navigate().back();
driver.navigate().forward();
Example
driver.findElement(By.linkText("Download")).click();
Thread.sleep(3000); //delay
driver.navigate().back();
driver.navigate().forward();
------------------------------------------------------------------------------------------------------------------------------
2. Go to the URL
6.Perform ACTION
1.Click and Hold the source WebElement
Example
Steps to make Single Select in Drop down through Selenium Web Driver.
Example
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();
}
}
------------------------------------------------------------------------------------------------------------------------------
Steps to make Single Select in Drop down through Selenium Web Driver.
Example
Thread.sleep(3000);
Thread.sleep(3000);
------------------------------------------------------------------------------------------------------------------------------
Steps to make Multiple Select in Drop down through Selenium Web Driver.
Example
------------------------------------------------------------------------------------------------------------------------------
2. Go to the URL
Example
------------------------------------------------------------------------------------------------------------------------------
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
driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
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
------------------------------------------------------------------------------------------------------------------------------
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);
------------------------------------------------------------------------------------------------------------------------------
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
TABS/New Window - 2
When two browsers are opened and Web Driver need to shift the control from Parent Window to Child Window.
------------------------------------------------------------------------------------------------------------------------------
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.
------------------------------------------------------------------------------------------------------------------------------
Calendar PopUp - 1
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();
}
}
}
------------------------------------------------------------------------------------------------------------------------------
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.
act.moveToElement(parentMenu).build().perform();
driver.findElement(By.linkText("Bharat Tirth")).click();
------------------------------------------------------------------------------------------------------------------------------
Example
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();
------------------------------------------------------------------------------------------------------------------------------
We can write code to fill up the text box through java script.
------------------------------------------------------------------------------------------------------------------------------
We can count the number of links present in the page. We can also print the link text of each Web link.
------------------------------------------------------------------------------------------------------------------------------
System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");
------------------------------------------------------------------------------------------------------------------------------
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");
------------------------------------------------------------------------------------------------------------------------------
1. Import Selenium.Proxy
import org.openqa.Selenium.Proxy
------------------------------------------------------------------------------------------------------------------------------
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.
5.Drag and Drop finder tool in AutoIt Window Info, to the Window you need to identify.
----------------------------------------------------AUTOIT CODE-----------------------------------------------------
WinWaitActive("Authentication Required")
Send("admin")
------------------------------------------------------------------------------------------------------------------------------
EXAMPLE:
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.
------------------------------------------------------------------------------------------------------------------------------
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.
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;
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();
}
}
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;
/**
* @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();
}
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.
/**
* @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();
}
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;
myTestDriver.get("http://tinyurl.com/cb3lbho");
Thread.sleep(5000L);
try {
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();
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);
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>
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;
//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;
}
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");
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(15));
driver.SwitchTo().Frame("canvas_frame");
}
}
}
The Below code searches for an item in the drop down and selects it
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;
/*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"));
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;
/**
* @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
*/
/**
* 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.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();
}
}
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;
/**
* 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);
/**
* 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
java.util.List<WebElement> f = driver.findElements(By.tagName("iframe"));
System.out.println(f.size());
if(f.size()>0) {
if(frameid.getAttribute("id").equals("frame_name"))
driver.switchTo().frame(frameid);
import java.io.File;
import org.apache.commons.io.FileUtils;
//Do some operation on child window and get child window handle.
String winHandleAfter = driver.getWindowHandle();
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 {
if (f.exists()) {
f.delete();
wr.write("\t\t\t"
+ "*******************************************************");
wr.newLine();
+ fileName.toUpperCase());
wr.newLine();
+ (System.getProperty("user.name")).toUpperCase());
wr.newLine();
wr.newLine();
+ Calendar.getInstance().getTime().toString());
wr.newLine();
wr.newLine();
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
*******************************************************
*******************************************************
Once the template is created the actual reporting comes into picture for which the code looks like this
String actual) {
try {
boolean append = true;
fbw.write("Step ");
fbw.write(stepCount + "");
fbw.write(" ");
fbw.write(Initialize.getDateFormat(Initialize.vDatetype9));
fbw.write(" ");
fbw.write(status.toUpperCase());
fbw.newLine();
fbw.write("----------------------------------------------------");
fbw.newLine();
fbw.newLine();
fbw.newLine();
fbw.newLine();
fbw.newLine();
fbw.close();
stepCount++;
} catch (Exception e) {
}
}
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
try {
writeToNotepad (PASS,
+ " - Successfull".toUpperCase());
} catch (Exception e) {
writeToNotepad (FAIL,
"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
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.
Where -
Usage
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.
return (String)TestParameterMap.get(key);
}
else{
return "Key not found";
}
}
For Eg
driver.navigate(getValue("KeyName"));
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.
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;
driver.manage().window().maximize();
WebElement oWE=driver.findElement(By.linkText("About Google"));
oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perf
orm();
if(driver.switchTo().window(sHandler).getTitle().equals("Google"))
{
driver.switchTo().window(sHandler);
WebElement oWE1=driver.findElement(By.linkText("+Google"));
oWE1.click();
}
}
}
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.
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"
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.
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.
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.
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.
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:
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-
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.
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.
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".
There is more the Regular Expressions but this information is what you need for most situations.
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.
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);
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
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. }
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,
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.
@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:
@FindBy(name="q")
private WebElement searchField;
@FindBy(name="btnG")
private WebElement searchButton;
public AnnotatedGoogleSearchPage(WebDriver driver) {
this.driver = driver;
}
WebDriver
During parallel execution of tests on FireFox you may encounter this error
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).
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.
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.
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();
}
}
Answer: Firefox
Answer: Globbing
Will be updated with more questions then and there. Keep visiting
Selenium RC
Answer: fireEvent()
Answer: Java
Will be updated with more questions then and there. Keep visiting
Selenium WebDriver
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.
driver.switchTo().frame("frame1");
driver.switchTo().frame("frame2");
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.
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.
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
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.
Using WebDriverBackedSelenium makes sense to easily migrate your test scripts from Selenium Rc to WebDriver.
selenium.stop();
You may use any WebDriver implementation, here we use Firefox Driver
//Selenium rc implementation
Selenium selenium = new DefaultSelenium(driver, strBaseurl);
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
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.
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
Listed below are the issues I had encountered and how I was able to overcome during the Webbriver migration
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
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
Create a custom Firefox profile and then import the certificate and add the below code to load the custom profile
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.
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
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.
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.
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.
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:
view plainprint?
1. WebDriver driver;
2. JavascriptExecutor js = (JavascriptExecutor) driver;
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>