Sunday 15 January 2012

Starting with selenium IDE


Selenium IDE: 


It can be used to build the test cases in Mozilla Firefox only

You Can Download Selenium IDE from Link :- http://seleniumhq.org/download/ 
Install the downloaded file and restart the browser

Selenium IDE works only on Mozilla, You can use this for record, play-back and language conversion

     How to create a test in selenium IDE:

·         Open/browse the site for which you want to prepare a test case.
·         Start Selenium IDE from Firefox Tools -> Selenium IDE
·         Perform your actions
·         Click red button to stop recording


To run your test click ‘Play Current test case’









Friday 13 January 2012

Data Driving With Selenium RC Using .csv file

Steps


1. Create your project in Eclipse
2. Add a jave class with name DataDrivingInSelenium to project
3. create a csv file and save it in  data folder of C drive


4. Run the class with junit


csv File("C:\\data\\MyData.csv")


First Name,Last Name
Shiv,Kumar Jha
Selenium,Test
Selenium,Shiv




DataDrivingInSelenium .java file




//write your package name
//package tests;

//import The Below Selenium class for starting server and application
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.SeleniumServer;

//The beow mentioned classes needs to be imported for reading the file
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.StringTokenizer;

//Defined the Class to parameterize the test
public class DataDrivingInSelenium extends SeleneseTestCase {

//Define the Setup mentod to invoke the base URL
public void setUp() throws Exception {
            SeleniumServer sServer = new SeleniumServer();
            sServer.start();
            selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.co.in/");
            selenium.start();
}
public void testDataDriveGoogle() throws Exception {

//Definition of .csv file to read
String sFileName = "C:\\data\\MyData.csv";
String sFirstName;
String sLastName;
String sFullName;
//Define CSV Data File variable
String [][] sTestData;

selenium.setSpeed("2000");
sTestData = this.readCSVFile(sFileName);

// This logic works for 3 rows 2 columns of your test data file
for (int iRow=1; iRow<4; iRow++) {

//Mapping the column numbers with column names
sFirstName = sTestData[iRow][0]; //refers to firstName in CSV
sLastName = sTestData[iRow][1]; //refers to lastName in CSV

// Concatinating the firstName and lastName
sFullName = sFirstName + " " + sLastName;
selenium.open("/");

//Entering the full name in the Google Text Field
selenium.type("q", sFullName);
selenium.click("btnG");
}

}
public String [][] readCSVFile(String sFileName) throws IOException, InterruptedException {

String [][] sCSVData = new String [15][15];
int iRow = 0;
int iCol = 0;
//String variable which takes each line at a time as a record
String sCurLine;

//A FileInputStream obtains input bytes from a file in a file system
FileInputStream fFileStream = new FileInputStream(sFileName);

//Data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way
DataInputStream dDataStream = new DataInputStream(fFileStream);

//Beginning of outer while loop to read each row in the data file
while ((sCurLine = dDataStream.readLine()) != null) {

//System.out.println(sCurLine);
StringTokenizer sTookens = new StringTokenizer(sCurLine,",");
//Beginning of inner while loop to read each column of the row in the data file
while (sTookens.hasMoreTokens())
{

//get next token as column and store it in the array
sCSVData[iRow][iCol] = sTookens.nextToken();
//System.out.println(sCSVData[iRow][iCol]);
iCol++;
Thread.sleep(1000);
} //End of inner while loop
iCol = 0;
iRow++;
} //Ending of outer while loop

return sCSVData;
} //End of CSV Read method

} // End of class file



Commonly used Selenium Commands


1.     Action Commands
                                        Open(Locator) – This Command will open the specified
                                        click(Locator) – This Command will Click at specified target
                                        check(Locator) – Toggles the checked value of a checkbox
                                        type(Locator, value) –Sends text input to an element
                                        select (Locator, value)– This will select the specified item in a list
Note: most action commands in Selenium IDE also have a duplicate command with the AndWait suffix.   When these are used the action is performed and a page load is expected and the command will not complete until the page has loaded or the timeout is reached.
2.     Store, Check, and Wait
·         store(expression, variableName) – Allows you to temporarily store a value
·         verify(pattern) – performs verification and skip execution, if fails.
·         assert(pattern)  – performs verification and stop execution, if fails.
·         waitFor(pattern)   – Waits until the value matches the specified value or the timeout.
Note: These Commands are heart of Selenium ,as these deal with verifiacation and validation part.

3.     Triggering Events

·         mouseDown / mouseUp(locator) – This simulates clicking the left mouse button.
·         keyDown / keyUp(locator, keySequence) – Simulate the user pressing a key or releasing a key.
·         fireEvent(locator, eventName) – If all else fails you can fire the JavaScript event directly.

 

Note:  When using the type and click commands, you might find that certain JavaScript events aren’t firing. For this reason there are several alternative commands that may help. Some of these are listed above.



Tuesday 10 January 2012

User Extension with Selenium IDE


Steps

  1. write the extension code into a new .js file. You can place it anywhere on your drive.
  2. Open Options - Options... in the menu bar.
  3. Choose the saved file in "Selenium Core Extensions" field and click OK.
  4. Restart Selenium IDE by closing the window and opening it again.

Sample Example of User-Extensions.js


Selenium.prototype.doTypeTodaysDate = function(locator){
var dates = new Date();
var day = dates.getDate();
if (day < 10){
day = '0' + day;
}
month = dates.getMonth() + 1;
if (month < 10){
month = '0' + month;
}
var year = dates.getFullYear();
var prettyDay = day + '/' + month + '/' + year;
this.doType(locator, prettyDay);
}


Above code will enter current date in dd/mm/yyyy format in specified Locator(Passeed as argument)

Note: - After adding above User-Extensions.js with selenium IDE , you can see additional command “TypeTodaysDate” in selenium ide command list. 

steps to call this function from ide
1. write command "TypeTodaysDate" in selenium IDE
2. Enter Locator in Target ( Locator of webedit , where you want to enter current date)
3. Run selenium IDE

Eclipse configuration for Selenium RC


Steps:
1. Create  your java project in eclipse
    -> Launch Eclipse
                -> Creat a java project named TestProject (for example)
2. Add Junit Library to your project
  ->  Go to Project Properties(Right Click on Project and click on Properties)
  ->  Go to Java Build Path
  ->  Click on Libraries tab
  ->  Click on 'Add Library' button
  ->  Select 'Junit' option from list and click on next
  ->  Select version 'Junit4' from drop down and click on finish.
3. Add required  Jar files into Project:
                ->  Go to Project Properties
                 ->  Go to Java Build Path
                 ->  Click on Libraries tab
                ->  Click on 'Add External Jars'  button
                ->  Browse for “selenium-java-client-driver.jar” and “selenium-server.jar”
4. Add your test (Java class )  in our Project
                ->  In eclipse go to create a new java class
->  Create it with name MyFirstTestCase (for example) and paste the code from file( record the application and convert to junit4 from selenium IDE)
                ->  Choose "com.thoughtworks.selenium.SeleneseTestCase" as its super class
 ->  Finish it
5. Add Steps to start selenium server
Write below line at the start of setUp() method.
SeleniumServer sServer = new SeleniumServer();
sServer.start();

Note :- write below line at the start of this test( next to package, if package exist)
            import org.openqa.selenium.server.SeleniumServer;
6. Change the browser name in  DefaultSelenium() method
            exp:- write *iexplore for internet explorer

7.Run the test
     
      Right click on project and choose run as junit

Selenium vs QTP





High Level Comparison
HP QTP 10
SELENIUM 1.0
Technical experience required to be successful

       *
        * * *
Web 1.0 Record/Playback
Rich Internet Application Using Ajax Support
            No
            Yes
Record Tests
MS IE 6, 7,Firefox 2,3
Firefox all versions

Playback

MS IE 6, 7,Firefox 2,3
All browser With all version
OS Compatibility
Only on Windows
Windows, Linux, Mac os,…..
Parallel Execution of Scripts
            No
       Yes
Language Support

VB-Script
Java,Ruby,Python,C#,PHP,Perl


Object Identification In Selenium


Element Locators tell Selenium which HTML element a command refers to.

Identifiers
Syntax1
Syntax2
Comments
id
id =id
id
Select the element with the specified @id attribute
name
name=username
username
Select the first element with the specified @name attribute
dom
dom=document.images[1]
Find an element using JavaScript traversal of the HTML DOM
xpath
xpath=//img[@alt='do]
//img[0]
Locate an element using an XPath expression
link
link=The link text
Select the link (anchor) element which contains text matching.
CSS
css=a[href="#id3"]
Select the element using css selectors