Friday, March 2, 2012

Selenium Webdriver (2.x) in Java Using TestNG

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

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


1. Setting up New Project in Eclipse



1.1 Create a new Java Project


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





1.3 Create a new Folder for library files and download all the java webdriver jar files. Copy the jar files from libs folder also



1.4 Configure the build Path

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

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


1.5 Create new Package under the src folder


1.6 Create a new java file


2. Copy and paste the below code


package com.test.webdriver;

import static org.testng.AssertJUnit.assertEquals;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

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



3. Run the Java Code as TestNG test




4. View the Emailable Report in TestNG output folder



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