Sunday, December 28, 2014


In this tutorial I will explain you how to download txt, pdf, csv, excel and doc file using firefox profile. You can write a selenium script to download file, if you know the MIME type of the file that you wanted to download.





Download File Using Selenium WebDriver

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class Training {
 static WebDriver driver;

 public static void main(String[] args) throws InterruptedException {

  FirefoxProfile firefoxprofile = new FirefoxProfile();

  firefoxprofile.setPreference("browser.download.dir", "D:\\download");
  firefoxprofile.setPreference("browser.download.folderList", 2);

  firefoxprofile
    .setPreference(
      "browser.helperApps.neverAsk.saveToDisk",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;"
        + "application/pdf;"
        + "application/vnd.openxmlformats-officedocument.wordprocessingml.document;"
        + "text/plain;" + "text/csv");
  firefoxprofile.setPreference(
    "browser.download.manager.showWhenStarting", false);
  firefoxprofile.setPreference("pdfjs.disabled", true);

  driver = new FirefoxDriver(firefoxprofile);

  driver.get("reditblog.blogspot.in/2014/12/how-to-download-file-using-selenium.html");

  driver.findElement(By.name("text")).click();
  Thread.sleep(5000);
  driver.findElement(By.name("pdf")).click();
  Thread.sleep(5000);

  driver.findElement(By.name("CSV")).click();
  Thread.sleep(5000);

  driver.findElement(By.name("Excel File")).click();
  Thread.sleep(5000);

  driver.findElement(By.name("Doc")).click();
  Thread.sleep(5000);

  driver.quit();

 }
}






In this tutorial I will explain how to click on WebElement using JavaScriptExecutor. Sometimes click() does not work then you can use JavaScriptExecutor to click button or WebElement.





Click WebElement Using JavaScriptExecutor

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Training {
 static WebDriver driver;

 public static void main(String[] args) throws InterruptedException {

  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.get("http:// www.google .com/");
  driver.findElement(By.name("q")).sendKeys("http://reditblog.blogspot.in");

  Thread.sleep(5000);
  WebElement element1 = driver.findElement(By.name("btnK"));
  JavascriptExecutor executor1 = (JavascriptExecutor) driver;
  executor1.executeScript("arguments[0].click();", element1);
  Thread.sleep(5000);
  WebElement element2 = driver.findElement(By.linkText("Reditblog"));
  JavascriptExecutor executor2 = (JavascriptExecutor) driver;
  executor2.executeScript("arguments[0].click();", element2);
  Thread.sleep(5000);
  driver.quit();
 }

}





Tuesday, December 16, 2014


If the WebDriver does not get web element then the WebDriver will wait for specified time and WebDriver will not try to search the element during the specified time. Once the specified time is over, WebDriver will start searching the web element only one time before throwing the exception.





Selenium Implicit Wait Example


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.firefox.FirefoxDriver;

public class Training {
 static WebDriver driver;

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to(
    "http://www. w3schools. com/js/tryit. asp?filename=tryjs_alert");

  driver.switchTo().frame(0);

  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  WebElement element = driver.findElement(By.tagName("button"));
  element.click();

  Alert alert = driver.switchTo().alert();

  System.out.println(alert.getText());
  Thread.sleep(5000);
  alert.accept();
 }

}





If a particular web element takes more than a minute to load then you may want to wait for the element to load properly and then go to the next line of code. In selenium, it is possible with Explicit Wait.





Selenium Explicit Wait Example


import org.openqa.selenium.Alert;
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.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Training {
 static WebDriver driver;

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to(
    "http:// www. w3schools. com/js/tryit. asp?filename=tryjs_alert");

  driver.switchTo().frame(0);

  WebElement element1 = (new WebDriverWait(driver, 10))
    .until(ExpectedConditions.elementToBeClickable(By
      .tagName("button")));
  WebElement element = driver.findElement(By.tagName("button"));
  element.click();

  Alert alert = driver.switchTo().alert();

  System.out.println(alert.getText());
  Thread.sleep(5000);
  alert.accept();
 }

}





Monday, December 15, 2014


This article shows you how to take screenshot using Selenium Webdriver. Screen shot may help you to identify and debug the problem.





Take Screenshot Using Selenium Webdriver

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Training {
 static WebDriver driver;

 public static void main(String[] args) {

  driver = new FirefoxDriver();
  driver.get("http://www.google.com");
  driver.manage().window().maximize();
  try {
   driver.findElement(
     By.xpath("//*[@id='Blog1]"))
     .sendKeys("test");

  } catch (Exception e) {
   System.out.println("Please look at D:\\screenshot.png for screenshot!");
   try {
    getscreenshot();
   } catch (Exception e1) {
    System.out.println(e1);
   }
  }
 }

 public static void getscreenshot() throws Exception {
  File scrFile = ((TakesScreenshot) driver)
    .getScreenshotAs(OutputType.FILE);

  FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));
 }

}







In this tutorial, I will tell you how to write text in the forms. Selenium webdriver provides a method called sedKeys() which help us to write text in the forms automatically.





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.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class Training {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.get("https:// login.yahoo. com/?.src=ym&.intl=us&.lang=en-US&.done=https%3a// mail.yahoo. com");
  driver.manage().window().maximize();
  driver.findElement(By.id("login-username")).sendKeys("some text");
  driver.findElement(By.id("login-passwd")).sendKeys("some password");

 }

}






Suppose we have a requirement to drag a webelement from one location and drop in another using a selenium script. In selenium webdriver, we can perform drag and drop or mouse operations by using Actions class.





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.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class Training {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.get("http: //jqueryui. com/droppable/");
  driver.manage().window().maximize();
  driver.switchTo().frame(0);
  driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
  WebElement dragElement = driver.findElement(By.id("draggable"));
  WebElement dropElement = driver.findElement(By.id("droppable"));

  Actions builder = new Actions(driver); 
  Action dragAndDrop = builder.clickAndHold(dragElement)
    .moveToElement(dropElement).release(dropElement).build();
  dragAndDrop.perform();

 }

}





Wednesday, November 12, 2014


In this tutorial, I will tell you how to delete cookies -

1. We need to create an object of cookie and pass the cookie name and value to the cookie's constructor as an argument.

2. Add cookie using selenium webdriver.

3. Now delete cookies using selenium webdriver.





Let's See The Example


import java.util.Set;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Training {

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();

  driver.navigate().to("http:// www.flipkart. com/");

  Cookie name = new Cookie("mycookie", "12345");
  driver.manage().addCookie(name);

  // Let's get the cookie's value
  Set<cookie> cookies = driver.manage().getCookies();
  for (Cookie getcookies : cookies) {
   System.out.println(getcookies);
  }

  /*
   * You can delete cookies in 3 ways 1. By name
   * driver.manage().deleteCookieNamed("CookieName");
   * 
   * 2. By Cookie driver.manage().deleteCookie(getcookies);
   * 
   * 3. All Cookies driver.manage().deleteAllCookies();
   */
  driver.manage().deleteAllCookies();

 }

}






In this tutorial, I will tell you how to add cookie -

1. We need to create an object of cookie and pass the cookie name and value to the cookie's constructor as an argument.

2. Now add cookie using selenium webdriver.





Let's See Example

import java.util.Set;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Training {

public static void main(String[] args) throws InterruptedException {

WebDriver driver = new FirefoxDriver();

driver.navigate().to("http:// www.flipkart. com/");

Cookie name = new Cookie("mycookie", "12345");
driver.manage().addCookie(name);

// Let's get the cookie's value
Set<cookie> cookies = driver.manage().getCookies();
for (Cookie getcookies : cookies) {
System.out.println(getcookies);
}

}

}







Output -



A cookie is a small file stored on the client computer by the server. If the user requests a web page then the server uses cookie information to identify the user. With selenium, you can create, get and delete cookies.

1. Create cookie - There are several ways to create cookie.

         a) Cookie name = new Cookie("cookieName", "cookieValue");
             driver.manage().addCookie(Cookie arg0);


Click here for example.





2. Get cookies data - There are several ways to get cookie.

         a) driver.manage().getCookies();
         b) driver.manage().getCookieNamed(String arg0);


Click here for example.


3. Delete cookie - There are several ways to delete cookie.

         a) driver.manage().deleteCookieNamed("String arg0");
         b) driver.manage().deleteCookie(Cookie arg0);
         c) driver.manage().deleteAllCookies();


Click here for example.






Tuesday, November 4, 2014


A JavaScript prompt box is used when you want the user to enter a value before going to a page.

When a prompt box pops up, the user will have to enter a value by using WebElement sendkeys("String str") methond and then click either "OK" or "Cancel" to proceed after entering an input value.

If the user clicks "OK" the prompt box will return the value. If the user clicks "Cancel" the box returns null.





JavaScript Prompt Box Example



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.firefox.FirefoxDriver;

public class PromptExample {

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to(
    "http : //w3schools. com/js/tryit.asp?filename=tryjs_prompt");

  driver.switchTo().frame(0);

  Thread.sleep(5000);
  WebElement element = driver.findElement(By.tagName("button"));
  element.click();

  Alert alert = driver.switchTo().alert();

  alert.sendKeys("Hello Selenium");
  System.out.println(alert.getText());
  Thread.sleep(5000);
  alert.accept();

 }

}







A JavaScript confirm popup box is used when you want the user to verify or accept something. In confirm box, the user can click either "OK" button or "Cancel" button to proceed.

If the user clicks on "OK" button, the confirm popup box will return true. If the user clicks on "Cancel" button, the confirm popup box will return false.





JavaScript Confirm Box Example


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.firefox.FirefoxDriver;

public class ConfirmExample {

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to(
    "http:// www.w3schools. com/js/tryit.asp?filename=tryjs_confirm");

  driver.switchTo().frame(0);

  Thread.sleep(5000);
  WebElement element = driver.findElement(By.tagName("button"));
  element.click();

  Alert alert = driver.switchTo().alert();

  System.out.println(alert.getText());
  Thread.sleep(5000);
  alert.accept();

 }

}








A JavaScript alert box is used to provide some information to the user. Alert box provides only "OK" button. So, the user will have to click "OK" to proceed.





JavaScript Alert Box


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.firefox.FirefoxDriver;

public class AlertExample {

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to(
    "http:// www.w3schools. com/js/tryit.asp?filename=tryjs_alert");

  driver.switchTo().frame(0);

  Thread.sleep(5000);
  WebElement element = driver.findElement(By.tagName("button"));
  element.click();

  Alert alert = driver.switchTo().alert();

  System.out.println(alert.getText());
  Thread.sleep(5000);
  alert.accept();

 }

}






JavaScript alert, confirm and prompt popup is an web element. To handle JavaScript alert, confirm and prompt popup, Selenium comes with Alert interface.

Selenium Alert interface provides methods to

1. Click "OK" button

2. Click "Cancle" button

3. Get text from popup boxes

4. Enter text to popup boxes


Alert Interface & It's Methods







1. To move control from main window or web page to the JavaScript popup box.

Alert alert = driver.switchTo().alert();


2. Click on "OK" button.

alert.accept();


3. Click on "Cancel" button.

alert.dismiss();


4. To enter text to popup boxes.

alert.sendKeys();


5. To get text from popup boxes.

alert.getText();







Frames is a web page within another web page. A web page can have one or more frames.

Each frame has its own unique numeric id and name. Selenium WebDriver uses this unique id or name to switch control between frames.





Syntax -

1. driver.switchTo().frame(int arg0);

2. driver.switchTo().frame(String arg0);

3. driver.switchTo().frame(WebElement arg0);


How To Switch Between Many Frames


import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Training {

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to(
    "http:// www.w3schools. com/js/tryit.asp?filename=tryjs_alert");

  driver.switchTo().frame(0);

  Thread.sleep(5000);
  WebElement element = driver.findElement(By.tagName("button"));
  element.click();

  Alert alert = driver.switchTo().alert();

  System.out.println(alert.getText());
  Thread.sleep(5000);
  alert.accept();
  driver.switchTo().defaultContent();

 }

}






Web page may have multiple windows. Multiple windows means a link on a web page of another web page. Current web page is called main window and other windows called child window.

Each window has its own unique alphanumeric id. Selenium WebDriver uses this unique id to switch control between multiple windows.





How To Switch Between Multiple Windows



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Training {

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.get("http://reditblog.blogspot.in/p/selenium.html");
  driver.manage().window().maximize();
  Thread.sleep(5000);
  String mainWindow = driver.getWindowHandle();

  WebElement element = driver
    .findElement(By
      .linkText("Org.Openqa.Selenium.Firefox. NotConnectedException"));

  element.click();

  Thread.sleep(5000);
  for (String windowHandle : driver.getWindowHandles()) {
   if(windowHandle.equals(mainWindow)){
    System.out.println("Main Window - " + " "+ windowHandle);
    driver.switchTo().window(windowHandle);    
    System.out.println(driver.getTitle());
    
   }else{
    System.out.println("Child Window - " + " "+ windowHandle);
    Thread.sleep(5000);
    driver.switchTo().window(windowHandle);
    Thread.sleep(5000);
    System.out.println(driver.getTitle());
    driver.switchTo().defaultContent();   
    
   }
   
  }

 }

}





Friday, October 31, 2014


In this tutorial, We will learn how to go forward to the next web page.


Forward To The Next Web Page


1. Go to "http:// www.facebook. com".

2. Click on forgot password link.

3. Come back to "http:// www.facebook. com".

4. Now forward to the next web page (i.e forgot password page).





import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumForward {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://  www.facebook. com");
  WebElement element = driver.findElement(By.linkText("Forgot your password?"));
  element.click();
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  driver.navigate().back();
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  driver.navigate().forward();

 }

}






Suppose we are in login page and then we clicked on forget password link. Now we are in forget password page and we want to go back to the login page.

Let's see how can we go back to the previous web page.

driver.navigate().back() - This command is used to go previous page.





Back To The Previous Web Page Example


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumBack {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://  www.facebook. com");
  WebElement element = driver.findElement(By.linkText("Forgot your password?"));
  element.click();
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  driver.navigate().back();

 }

}






Sometimes we need to refresh the current web page to reload or to get the new dynamic value.

 driver.navigate().refresh() - This command is used to refresh the current page.

Refresh Current Web Page Example






import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumRefresh {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http:// www.google. com");
  WebElement element = driver.findElement(By.name("q"));
  element.sendKeys("Selenium");
  driver.navigate().refresh();

 }

}





Tuesday, October 28, 2014


In this tutorial, I will show you how to resolve WebDriver Exceptions.

1. Firefox - You may have faced org.openqa.selenium.firefox.NotConnectedException error.

To resolve this error, we need to download new version of Selenium. You can download Selenium from "http:// docs.seleniumhq. org/download/" and then extract the Selenium folder. Add all the JARs files from Selenium folder to your project.


2. Chrome - You may have faced java.lang.IllegalStateException error for chrome.

To resolve this error, You need to download chrome browser driver from "http:// www.seleniumhq. org/download/" and then extract. 







Add few lines of code -

System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");       
WebDriver driver = new ChromeDriver();

3. Internet Explorer - You may have faced java.lang.IllegalStateException error for Internet Explorer.


To resolve this error, You need to download Internet Explorer browser driver from http:// www.seleniumhq. org/download/ and then extract.

Add few lines of code -

        System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");  
    
        DesiredCapabilities cap
abilities = DesiredCapabilities.internetExplorer();
        cap
abilities.setCapability("ignoreZoomSetting", true);

        WebDriver driver = new InternetExplorerDriver(capabilities);






Monday, October 27, 2014


In my earlier posts, we have learned WebDriver's Drivers, WebDriver's Commands. In this tutorial, we will learn how to navigate on specific page or URL.

1. get(String URL) - This method will load a web page of given URL in the current browser.

Example: driver.get(“www.google.com”);


2. driver.navigate().to(String URL) - This method will load a web page of given URL in the current browser.

Example: driver.navigate().to("http://www.google.com");


Difference between get() and navigate()


Both navigate().to() and get() do exactly the same thing but with navigate we can go to the next page OR come back to the previous page OR refresh the current page.

1. driver.navigate().forward() - This command is used to go next page. Click here for example.

2. driver.navigate().back() - This command is used to go previous page. Click here for example.

3. driver.navigate().refresh() - This command is used to refresh the current page. Click here for example.







WebDriver Navigate() Example



import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class NavigateExample {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://www.google.com");
  WebElement element = driver.findElement(By.name("q"));
  element.sendKeys("Selenium");
  element.submit();

 }

}






Let's see how to list excepted exceptions that a test method can throw. If the test method throw no exception or throw other than excepted exceptions then the test will be marked a failure.

In the below example, there are two test methods -

1. exceptionTest - This test method result will be pass because the actual and expected exceptions is same (i.e. ArithmeticException).

2. exceptionTest1 - This test method result will be fail because the actual and expected exceptions is different.





Example Of TestNG expectedExceptions


import org.testng.annotations.Test;

public class ExceptedExceptionTest {

 @Test(expectedExceptions = ArithmeticException.class)
 public void exceptionTest(){
  int i = 6 / 0;
  
 }
 
 @Test(expectedExceptions = ArithmeticException.class)
 public void exceptionTest1(){
  int i = 65675.7676 / 2;
  
 }
 

}


Output:







Saturday, October 25, 2014


In this tutorial, We will see how to set maximum time for test case execution. If the test case takes more time than the specified time to finish then the TestNG will market it as failed.

To set maximum time for test case execution, we use timeOut attribute of @Test annotation.





TestNG timeOut Example


import org.testng.annotations.Test;

public class TimeOutTestCase {

 @Test
 public void LoginTest(){
  System.out.println("LoginTest test case is Passed");
 }
 
 // time in mulliseconds
 @Test(timeOut = 5000)
 public void WorkflowTest(){
  // System.out.println(" Ignore this test case.");
  try{
   Thread.sleep(6000);
  }catch(Exception e){
   System.out.println(e);
  }
 }
 
 @Test
 public void LogoutTest(){
  System.out.println("LogoutTest test case is Passed");
  System.out.println(" ");
 }

}

Output:









In this tutorial, we will see how to ignore test case. Sometimes, We need to ignore test cases. In this example, We will ignore WorkflowTest test case.

TestNG comes with annotation @Test and attribute "enabled". We need to make enabled equal to false.





TestNG Ignore Test Case Example


import org.testng.Assert;
import org.testng.annotations.Test;

public class IgnoreTestCase {

 @Test
 public void LoginTest(){
  System.out.println("LoginTest test case is Passed");
 }
 
 @Test(enabled = false)
 public void WorkflowTest(){
  System.out.println(" Ignore this test case.");
 }
 
 @Test
 public void LogoutTest(){
  System.out.println("LogoutTest test case is Passed");
  System.out.println(" ");
 }

}

Output:







Thursday, October 23, 2014




In this tutorial, I will list out Selenium WebElement methods. WebElement in a web page is nothing but a text box, button, links, checkbox, radio button, table, window, frames etc.


Selenium WebElement Methods


 1. clear() - This method is used to clear the value of text box.

Example: driver.findElement(By.name(“username”)).clear();



2. click() - This method is used to click on the selected WebElement.

Example: driver.findElement(By.name(“submit”)).click();



3. getAttribute(java.lang.String name) - This method is used to get the value from the fields like Text box.

Example: driver.findElement(By.className(“Blogercup”)).getAttribute(“username”);



4. getSize() - This method is used to get the size of the WebElement.



5. getTagName() - This method is used to get the tag name of the selected WebElement.





6. getText() - This method is used to get text from the selected WebElement of the web page.

Example:

List<WebElement> element = driver.findElements(By.name(“q”));

for(int i=0;i<element.size();i++){

System.out.println(element.get(i).getText());

}



7. sendKeys(java.lang.CharSequence… keysToSend) - This method is used to type text in the selected WebElement

Example:

WebElement element = driver.findElement(By.name(“q”));

element.sendKeys(“Blogercup”);



8. submit() - This method is used to submit a form.

Example:

WebElement element = driver.findElement(By.name(“q”));

element.submit();








In this tutorial, I will list out Selenium WebElement locator. WebElement’s locators used to find all WebElements within a web page.

Selenium WebElement Locator

 

1. findElements() - This method is used to find all WebElements within a web page with same locator.

Example: List<WebElement> element = driver.findElements(By.name(“q”));



2. findElement() -  This method is used to find the first WebElement within a web page.

Example: WebElement element = driver.findElement(By.name(“q”));



3. By ID - This is a WebElement’s locator and used to find WebElement within a web page using WebElement’s id.

Example: WebElement element = driver.findElement(By.id(“q”));



4. By Name - This is a WebElement’s locator and used to find WebElement within a web page using WebElement’s name.

Example: WebElement element = driver.findElement(By.name(“q”));



5. By Tag Name - This is a WebElement’s locator and used to find WebElement within a web page using WebElement’s tagName.

Example: WebElement frame = driver.findElement(By.tagName(“q”));





6. By XPATH - This is a WebElement’s locator and used to find WebElement within a web page using WebElement’s xpath.

Example: WebElement element = driver.findElements(By.xpath(“//input”));



7. By CSS - This is a WebElement’s locator and used to find WebElement within a web page using WebElement’s css.

Example: WebElement element = driver.findElement(By.cssSelector(“#q span.text.name”));



8. By Class Name – This is a WebElement’s locator and used to find WebElement within a web page using WebElement’s className.

Example: List<WebElement> element = driver.findElements(By.className(“q”));



9. By Link Text - This is a WebElement’s locator and used to find WebElement within a web page using WebElement’s linkText.

Example: WebElement element = driver.findElement(By.linkText(“q”));



10. By Partial Link Text - This is a WebElement’s locator and used to find WebElement within a web page using WebElement’s partialLinkText.

Example: WebElement element = driver.findElement(By.partialLinkText(“q”));








WebDriver is an interface in Selenium. WebDriver provides a set of methods that we use to automate web application for testing purpose.


1. get(String URL) - This method will load a web page of given URL in the current browser.

Example: driver.get(“www.google.com”);


2. getCurrentUrl() – This method will return a string representing URL of the current web page that the browser is looking at.

Syntax: driver.getCurrentUrl();


3. getTitle() - This method will return title of the current web page.

Syntax: driver.getTitle();


4. getPageSource() - This method will provide you the source of the last loaded page.

Syntax: driver.getPageSource();


5. close() - If there is multiple windows opened, this method will close the current window and quit the browser, if the current window is the last window opened.

Syntax: driver.close();


6. quit() - Quits all the windows opened.

Syntax: driver.quit();


7. getWindowHandles() - Return a set of string representing window handles which can be used to iterate over all open windows of this WebDriver instance by passing them to switchTo().WebDriver.Options.window().

Syntax: driver.getWindowHandles();


8. getWindowHandle() - Return a string representing window handle of the main window that uniquely identifies it within this driver instance.

Syntax: driver.getWindowHandle();





9. manage() - Gets the Option interface.

Example: driver.manage().addCookie(cookie);


Selenium WebDriver Commands Example


package testng;
 
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;
 
public class SeleniumDriver {
 
    public static void main(String[] args) {
 
        System.setProperty("webdriver.ie.driver",
                "C:\\Program Files\\Internet Explorer\\iexplore.exe");
 
        WebDriver driver = new FirefoxDriver();
 
        driver.get("http://www.google.com");
 
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 
        WebElement element = driver.findElement(By.name("q"));
 
        System.out.println("URl of current web page -" + " "
                + driver.getCurrentUrl());
 
        element.sendKeys("Selenium!");
 
        System.out.println("Title of current web page -" + " "
                + driver.getTitle());
 
        System.out.println("Window Handle -" + " " + driver.getWindowHandle());
 
        System.out.println("Page Source -" + " " + driver.getPageSource());
 
        driver.close();
 
    }
}








Selenium WebDriver’s driver (i.e. browser driver) is required to make a direct calls to the browser using browser’s native support for automation.

In selenium, FirefoxDriver, InternetExplorerDriver, ChromeDriver and HtmlUnitDriver is a class which implements WebDriver interface.


Selenium WebDriver’s Driver For Different Browsers


1. Firefox Driver: Let’s see how to create Firefox browser’s driver object -

  • WebDriver driver = new FirefoxDriver();


2. Chrome Driver: Let’s see how to create Chrome browser’s driver object -

  • WebDriver driver = new ChromeDriver();





3. Internet Explorer Driver: Let’s see how to create Internet Explorer browser’s driver object -

  • WebDriver driver = new InternetExplorerDriver();


4. HtmlUnit Driver: Let’s see how to create HtmlUnit browser’s driver object -

  • WebDriver driver = new HtmlUnitDriver();


Selenium WebDriver’s Driver Example


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class SeleniumDriver {
 
    public static void main(String[] args) {
 
        // Create object of the Firefox driver
        WebDriver driver = new FirefoxDriver();
 
        // Open Google       
        driver.get("http://www.google.com");
 
        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));
 
        // Enter text to search for
        element.sendKeys("Selenium!");
 
    }
}








TestNG provides “@Test” annotation along with attribute “dependsOnMethods”. There may be a requirement to make a test case to depends on other test cases. To make a test case to depends on other test cases, we need to use dependsOnMethods attribute with @Test annotation.

 DependsOnMethods Testng Example

 
There are three test cases named “LoginTest”, “WorkflowTest” and “LogoutTest”.

1. WorkflowTest depends on LoginTest. If LoginTest test case failed then WorkflowTest test case will skipped.

2. LogoutTest depends on LoginTest and WorkflowTest test cases. If LoginTest or WorkflowTest test case failed then LogoutTest test case will skipped.





TestNG DependsOnMethods


import org.testng.Assert;
import org.testng.annotations.Test;
 
public class TestCasePriority {
 
    @Test(priority=1)
    public void LoginTest(){
        Assert.assertEquals("true", "false");
    }
 
    @Test(priority=2, dependsOnMethods={"LoginTest"})
    public void WorkflowTest(){
        System.out.println(" This test case should Skipped, if LoginTest test case Failed");
    }
 
    @Test(priority=3, dependsOnMethods={"LoginTest", "WorkflowTest"})
    public void LogoutTest(){
        System.out.println(" This test case should Skipped, if LoginTest or WorkflowTest test case Failed");
        System.out.println(" ");
    }
 
}








We need to set priority of test cases to execute test case in a particular order. If we do not set priority of test cases then we are not sure the order of execution of test case (i.e. Logout test case may run or execute before Login test case).

Steps to test an application


1. Login

2. Workflow

3. Logout


There is three test cases


1. Login test case

2. Workflow test case

3. Logout test case





How to set priority of test cases


import org.testng.annotations.Test;
 
public class TestCasePriority {
     
    @Test(priority=1)
    public void LoginTest(){
        System.out.println(" Login Test case should execute first");
    }
     
    @Test(priority=2)
    public void WorkflowTest(){
        System.out.println(" Workflow Test case should not execute before Login test case");
    }
     
    @Test(priority=3)
    public void LogoutTest(){
        System.out.println(" Logout should not execute before Login and Workflow test cases");
        System.out.println(" ");
    }
 
}





Thursday, August 21, 2014




In this tutorial, I will tell you how to configure Selenium with eclipse. Before you configure Selenium with eclipse, You should be sure that you have installed TestNG plugin with eclipse. Click here to know how to install and configure TestNG with Eclipse.

Steps To Configure Selenium With Eclipse

1. First you need to download Selenium from “http://docs.seleniumhq.org/download/“  and then extract the Selenium folder.






2. Open eclipse and create project. Right click on project –> Properties –> Java Build Path –> click on “Libraries tab” –> click on “Add External JARs” button –> add all JARs files from Selenium folder.



3. Close and Re-open eclipse.

4. Right click on project –> Refresh

5. Project –> clean project.

Selenium installation with eclipse is done. Thanks for reading how to configure selenium with eclipse.





Thursday, August 14, 2014




In this tutorial, I will introduce you with TestNG annotations list. TestNG acts as a controller. TestNG controls the flow of execution of code with the help of annotations.

TestNG Annotations List


Annotations Description
@BeforeSuite The annotated method will run before all test methods run in this suite.
@AfterSuite The annotated method will run after all test methods run in this suite.
@BeforeTest The annotated method will run before any test method belonging to the classes.
@AfterTest The annotated method will run after all the test methods belonging to the classes.
@BeforeGroups The annotated method will run before the first test method that belongs to any of these groups is invoked.
@AfterGroups The annotated method will run after the last test method that belongs to any of these groups is invoked.
@BeforeClass The annotated method will run before the first test method run in the current class.
@AfterClass The annotated method will run before all the first test methods run in the current class.
@BeforeMethod The annotated method will run before each test method.
@AfterMethod The annotated method will run after each test method.
@DataProvider The annotated method provide data to the @Test methods. The annotated method returns an Object[][].
@Test The annotated method contains test cases.


To understand more about TestNG Annotations and attributes (i.e. @Test, @DataProvider,... etc) with examples then look at Data-Driven Framework tutorial.





Let's understand the TestNG Annotations list with an example


package testng;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestNGAnnotations {

 @BeforeSuite
 public void instantiate() {
  System.out.println("Instantiate Object");
 }

 @BeforeTest
 public void dataBaseConnection() {
  System.out.println("Database Connected");
 }

 @BeforeMethod
 public void BeforeMethod() {
  System.out.println("Run before each Test Case.");
 }

 @Test
 public void testCase1() {
  System.out.println("First Test Case Result..... ");
 }
 
 @Test
 public void testCase2() {
  System.out.println("Second Test Case Result.... ");
 }

 @AfterMethod
 public void AfterMethod() {
  System.out.println("Run after each Test Case");
 }

 @AfterTest
 public void dataBaseDisconnection() {
  System.out.println("Database Disconnected");
 }

 @AfterSuite
 public void destory() {
  System.out.println("Destory Object");
 }
}

 

How To Create testng.xml


testng.xml: Right click on Project --> TestNG --> Convert to TestNG.



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="none">
  <test name="Test">
    <classes>
      <class name="testng.TestNGAnnotations"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->



How To Run Or Execute TestNG


Right click on testng.xml --> Run As --> TestNG Suite OR Right click on java file --> Run As --> TestNG Test


Output:

TestNG annotations list


Thanks for reading TestNG Annotations List.








In this tutorial, I will explain you TestNG installation in eclipse. TestNG comes with Eclipse plug-in that allow you to write and run TestNG tests from Eclipse in a convenient way. Before TestNG installation and configuration, you should be sure that the eclipse and java jdk 5 or higher has installed on the computer.

Once you are done with TestNG plugin installation, you need to add testng.jar in your project library. TestNG.jar comes with Selenium. So, I recommend you to configure Selenium with eclipse. Click here to know how to install Selenium WebDriver.


TestNG Installation in Eclipse

Look at the following steps for TestNG Installation in Eclipse -

Sept 1: Open eclipse, click on "Help" and then click on "Install New Software".



Step 2: Enter site URL and click on "Add " button
  • For Eclipse 3.4 and above, enter http://beust.com/eclipse.
  • For Eclipse 3.3 and below, enter http://beust.com/eclipse1.










Step 3: Enter Repository Name (For example, Enter Name as “TestNG”) and Click "OK" Button and then Click Next button











Step 4: Accept the License and then click "Finish" button
















Step 5: Wait for Installing Software











Step 6: Click Ok

















Step 7: Restart Eclipse. Click "Yes" button


 

 

 

 

How to verify that TestNG has successfully installed?


Open eclipse, click Window --> Show View --> Other






















New window will open, click on Java. You will see TestNg inside the Java folder. This shows that TestNG has successfully installed in the eclipse.






















Click here to know how to install or configure Selenium WebDriver with eclipse. Thanks for reading TestNG installation in eclipse.