as

Friday, 6 September 2013

How to automate test cases using selenium in JAVA?

In this article I will tell you how we can do web automation using selenium in JAVA.

What you need to start with...
You will need to download below software to start automation

  1. Selenium API - https://code.google.com/p/selenium/downloads/list
  2. Webdriver for Interenet Explorer - https://code.google.com/p/selenium/downloads/list
  3. Webdriver for Chrome - https://code.google.com/p/chromedriver/downloads/list
  4. Eclipse  - Java IDE
Once you have these softwares with you, You can follow below steps.
  1. Open Eclipse and create new Java Project.
  2. Create a package and class with name SampleTest in it.
  3. Go to project properties and select Java build path. Select libraries tab and then choose add external jar.
  4. Browse to the jar file you have downloaded in step 1 first list.
  5. Select apply and close
Source code of SampleTest.java is given below.



package seleniumpackage;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

//import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor;
//import org.openqa.selenium.firefox.*;

@SuppressWarnings("unused")
public class SampleTest {
    
public static void main(String [] arg) 
{
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver =  new ChromeDriver();

        // System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
//wd =  new InternetExplorerDriver();
try{
//Install selenium 2.0 -> https://code.google.com/p/selenium/downloads/list
//Install chromedriver -> https://code.google.com/p/chromedriver/downloads/list
//Install IEDriver     -> https://code.google.com/p/selenium/downloads/list
//Get Eclipse          -> Java IDE

//***********************************************************************
// List of common operations on web elements
//***********************************************************************
//We will see lot of operation that can be done in selenium 
//1.Clicking on the WebElement.
//2.Enter value in editbox WebElement.
//3.Select value from the dropdown WebElement.
//4.Select radiobutton WebElement.
//5.Select the checkbox WebElement.
//6.Clicking/accessing hidden WebElements. -> Make them visible first and then click
//7.How to check if element exists in page.
//8.reading data from table rows, cells etc.
//9.Different ways of accessing elements.
//10.Synchronization methods in selenium in Java.
driver.navigate().to("http://www.google.com");
Thread.sleep(5000);
/* Check if element is present or Not */
Boolean isPresent = driver.findElements(By.id("lst-ib")).size()<0;
System.out.println("Element is present  " + isPresent );
/*Check if element is displayed in selenium */
System.out.println ( "Element with id visible -> " + driver.findElement(By.id("gb_51")).isDisplayed());
System.out.println ( "Element with id visible -> " + driver.findElement(By.name("q")).isDisplayed());
/*click on the webelelment */
driver.findElement(By.linkText("News")).click();
/*enter value in the edit box */
driver.findElement(By.name("q")).sendKeys("Selenium");
 
      /*Select value from drop down*/
//Select select=new Select(driver.findElement(By.id("abc")));
       //select.selectByVisibleText("=");   
/* Peforming mouseOver Event on the WebElement*/
//Actions builder = new Actions(driver);
                //Action hoverAction = builder.moveToElement(WE).build();
                //hoverAction.perform();
/*Accessing data from webtable */
/*
WebElement r =  wd.findElement(By.xpath("//*[@id='acd']/table/thead/tr"));
List<WebElement> cells = r.findElements(By.tagName("th"));
        int c = 0;
    for (WebElement cell : cells) {
       c=c+1;
       System.out.println(c + " --> "+ cell.getText() );
    if (head.equals(cell.getText()))
    break;
    }
    */
/*Wait until Element is present */
//WebElement me = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("myid")));
/*Wait until Element is clickable */
//WebDriverWait wait = new WebDriverWait(driver, 10);
//me = wait.until(ExpectedConditions.elementToBeClickable(By.id("myid")));
/*Implicit waits */
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
/* Locating elements */
//WebElement frame = driver.findElement(By.tagName("iframe"));
//List<WebElement> cheeses = driver.findElements(By.className("cheese"));
//WebElement cheese = driver.findElement(By.name("cheese"));
//WebElement element = driver.findElement(By.id("coolestWidgetEvah"));
//WebElement cheese = driver.findElement(By.linkText("cheese"));
//WebElement cheese = driver.findElement(By.partialLinkText("cheese"));
//WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));
//List<WebElement> inputs = driver.findElements(By.xpath("//input"));
/*We can also execute java script*/ 
//WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]");
//List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
//    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
 //  "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
/* Getting all options in drop down */
/*
WebElement select = driver.findElement(By.tagName("select"));
List<WebElement> allOptions = select.findElements(By.tagName("option"));
for (WebElement option : allOptions) {
   System.out.println(String.format("Value is: %s", option.getAttribute("value")));
   option.click();
}
*/
/* Selecting from dropdown
 
Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();
select.selectByVisibleText("Edam");
*/
//Alert alert = driver.switchTo().alert();
//driver.navigate().forward();
//driver.navigate().back();
//driver.get("www.google.com");
 //***************************************************************
// List of common Exception while working with WebElements
//*********************************************************************
//1."Element is not clickable at point (x, y). 
//2.No Such Element - for Frame related issue
//3.The driver executable does not exist
//4.Driver executable must be set by the webdriver.ie.driver system property
//5.The path to the driver executable must be set by the webdriver.chrome.driver system property
}
catch(Exception e){
System.out.println("Exception - > " + e.toString());
}
finally{
driver.close();
driver.quit();
}
    
}
}




This is how we can automate any web browser using selenium



What do you think on this topic? Please express your opinion through comment below

No comments:

Post a Comment

Leave your valuable feedback. Your thoughts do matter to us.

Sponsored Links

Popular Posts

Comments

ShareThis