Sunday, June 5, 2011

Simple code for Unit Test using WebDriver / Selenium 2

Following is a simple java test to do some testing using Selenium 2 in java.


package com.cisco.swtg.testing;

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;

public class Selenium2Example {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.bin","%HOMEPATH%\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe");
System.setProperty("webdriver.chrome.driver","c:\\chromedriver.exe");
System.setProperty("webdriver.firefox.bin","C:\\FirefoxPortableLegacy35\\FirefoxPortable.exe");
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver chromedriver=null;
WebDriver driver = new ChromeDriver();//new InternetExplorerDriver();// new HtmlUnitDriver();// FirefoxDriver();ChromeDriver
if (driver instanceof ChromeDriver){
chromedriver = (ChromeDriver)driver;

//chromedriver.findElement(By.id("Enter id here"));
}else {
if (driver instanceof FirefoxDriver)
chromedriver= (FirefoxDriver)driver;
else {
if (driver instanceof HtmlUnitDriver)
chromedriver= (HtmlUnitDriver)driver;
}
}
// And now use this to visit Google
chromedriver.get("http://www.cisco.com/cisco/psn/sasi");

// Find the text input element by its name
WebElement element = chromedriver.findElement(By.id("userInput"));
// FirefoxWebElement ele=(FirefoxWebElement) driver.findElement(By.name("USER"));;


// Enter something to search for
element.sendKeys("your - username");

WebElement element2 = chromedriver.findElement(By.name("PASSWORD"));
element2.sendKeys("your-password");

WebElement element3 = chromedriver.findElement(By.name("login-button"));
element3.submit();

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// Now submit the form. WebDriver will find the form for us from the element
// element.submit();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



chromedriver.findElement(By.id("searchTextBox")).sendKeys("gagandsi");
chromedriver.findElement(By.id("searchButton")).submit();
WebElement username= chromedriver.findElement(By.className("ft-label"));
chromedriver.findElements(By.className("ft-label"));
username.getText();
if(chromedriver.getPageSource().contains("UserName"))
System.out.println("User logged in Successfully");
// Check the title of the page
System.out.println("Page title is: " + chromedriver.getTitle());

//Close the browser
chromedriver.quit();
}
}


No comments: