Thursday, 13 February 2014

EventFiringWebDriver | AbstractWebDriverEventListener

Every tests should undergo WebDriverEventListener for analyzing tests and for better reporting. This post is very Generic and anyone can easily understand the concepts.

Note|
1| There are more to do and customize with the WebDriver EventListeners. Explained below is the most important functions under WebDriver EventListeners.
2| In the given example, make sure all the sections are commented out except one which you are working on. eg., if you working on 'onException' then comment out the other sections

EventFiringWebDriver supports registering of a WebDriverEventListener. Create a test class as shown below.

import org.openqa.selenium.support.events.EventFiringWebDriver;

public class className {
private WebDriver driver;

@BeforeTest
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
}

@Test
public void Test01() throws Exception {

EventFiringWebDriver event = new EventFiringWebDriver(driver);
WebDriverListerners eventListener = new WebDriverListerners();
event.register(eventListener);

                // beforeNavigateTo & afterNavigateTo
                event.get("http://www.google.com");

                // beforeNavigateBack & afterNavigateBack
                event.get("http://www.google.com");
                event.get("http://www.bing.com");
event.navigate().back();

                // beforeNavigateForward & afterNavigateForward
                event.get("http://www.google.com");
event.get("http://www.bing.com");
event.navigate().back();
event.navigate().forward();                   

                // onException
                event.get("http://.........");
event.findElement(By.id("Wrong Value"));

                // beforeFindBy & afterFindBy
                event.get("http://.........");
event.findElement(By.id("Value"));

                // beforeClickOn & afterClickOn
                event.get("http://.........");
event.findElement(By.id("Value")).click();

                // beforeChangeValueOf & afterChangeValueOf
                event.get("http://.........");
event.findElement(By.id("Value")).clear();
                event.findElement(By.id("Value")).sendKeys("Seleniumworks");
       }
}



AbstractWebDriverEventListener

Use AbstractWebDriverEventListener as a Base class for implementing WebDriverEventListener.


package packagename;

import java.io.File;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;

public class WebDriverListerners extends AbstractWebDriverEventListener {
private By lastFindBy;
private WebElement lastElement;
private String originalValue;

/*
 *  URL NAVIGATION | NAVIGATE() & GET()
 */
// Prints the URL before Navigating to specific URL "get("http://www.google.com");"
@Override
public void beforeNavigateTo(String url, WebDriver driver) {
System.out.println("Before Navigating To : " + url + ", my url was: "
+ driver.getCurrentUrl());
}

// Prints the current URL after Navigating to specific URL "get("http://www.google.com");"
@Override
public void afterNavigateTo(String url, WebDriver driver) {
System.out.println("After Navigating To: " + url + ", my url is: "
+ driver.getCurrentUrl());
}

// Prints the URL before Navigating back "navigate().back()"
@Override
public void beforeNavigateBack(WebDriver driver) {
System.out.println("Before Navigating Back. I was at "
+ driver.getCurrentUrl());
}

// Prints the current URL after Navigating back "navigate().back()"
@Override
public void afterNavigateBack(WebDriver driver) {
System.out.println("After Navigating Back. I'm at "
+ driver.getCurrentUrl());
}

// Prints the URL before Navigating forward "navigate().forward()"
@Override
public void beforeNavigateForward(WebDriver driver) {
System.out.println("Before Navigating Forward. I was at "
+ driver.getCurrentUrl());
}

// Prints the current URL after Navigating forward "navigate().forward()"
@Override
public void afterNavigateForward(WebDriver driver) {
System.out.println("After Navigating Forward. I'm at "
+ driver.getCurrentUrl());
}


/*
 * ON EXCEPTION | SCREENSHOT, THROWING ERROR
 */
// Takes screenshot on any Exception thrown during test execution
@Override
public void onException(Throwable throwable, WebDriver webdriver) {
System.out.println("Caught Exception");
File scrFile = ((TakesScreenshot) webdriver)
.getScreenshotAs(OutputType.FILE);
try {
org.apache.commons.io.FileUtils.copyFile(scrFile, new File(
"C:\\Testfailure.jpeg"));
} catch (Exception e) {
System.out.println("Unable to Save");
}
}


/*
 * FINDING ELEMENTS | FINDELEMENT() & FINDELEMENTS()
 */
// Called before finding Element(s)
@Override
public void beforeFindBy(By by, WebElement element, WebDriver driver) {
lastFindBy = by;
System.out.println("Trying to find: '" + lastFindBy + "'.");
System.out.println("Trying to find: " + by.toString()); // This is optional and an alternate way
       }

// Called after finding Element(s)
@Override
public void afterFindBy(By by, WebElement element, WebDriver driver) {
lastFindBy = by;
System.out.println("Found: '" + lastFindBy + "'.");
System.out.println("Found: " + by.toString() + "'."); // This is optional and an alternate way
}


/*
 * CLICK | CLICK()
 */
// Called before clicking an Element
@Override
public void beforeClickOn(WebElement element, WebDriver driver) {
System.out.println("Trying to click: '" + element + "'");
// Highlight Elements before clicking
for (int i = 0; i < 1; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
"arguments[0].setAttribute('style', arguments[1]);",
element, "color: black; border: 3px solid black;");
}
}

// Called after clicking an Element
@Override
public void afterClickOn(WebElement element, WebDriver driver) {
System.out.println("Clicked Element with: '" + element + "'");
}


/*
 * CHANGING VALUES | CLEAR() & SENDKEYS()
 */
// Before Changing values
@Override
public void beforeChangeValueOf(WebElement element, WebDriver driver) {
lastElement = element;
originalValue = element.getText();

// What if the element is not visible anymore?
if (originalValue.isEmpty()) {
originalValue = element.getAttribute("value");
}
}

// After Changing values
@Override
public void afterChangeValueOf(WebElement element, WebDriver driver) {
lastElement = element;
String changedValue = "";
try {
changedValue = element.getText();
} catch (StaleElementReferenceException e) {
System.out
.println("Could not log change of element, because of a stale"
+ " element reference exception.");
return;
}
// What if the element is not visible anymore?
if (changedValue.isEmpty()) {
changedValue = element.getAttribute("value");
}

System.out.println("Changing value in element found " + lastElement
+ " from '" + originalValue + "' to '" + changedValue + "'");
}


/*
 * SCRIPT - this section will be modified ASAP
 */
// Called before RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[])
@Override
public void beforeScript(String script, WebDriver driver) {
// TODO Auto-generated method stub
       }

// Called before RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[])
  @Override
        public void afterScript(String script, WebDriver driver) {
// TODO Auto-generated method stub
       }



OUTPUT |URL NAVIGATION | NAVIGATE() & GET()|
beforeNavigateTo & afterNavigateTo
Before Navigating To : http://www.google.com, my url was: about:blank
After Navigating To: http://www.google.com, my url is: https://www.google.co.in/?gfe_rd=cr&ei=qsb8Ur6bMqHM8gett4DoAQ

beforeNavigateBack & afterNavigateBack
Before Navigating Back. I was at http://www.bing.com/

After Navigating Back. I'm at https://www.google.co.in/?gfe_rd=cr&ei=Nsj8UqKwEoLV8gfnzYDwBQ

beforeNavigateForward & afterNavigateForward
Before Navigating Forward. I was at https://www.google.co.in/?gfe_rd=ctrl&ei=bMn8UonqD8PM8ge66YHICA&gws_rd=cr

After Navigating Forward. I'm at http://www.bing.com/

OUTPUT |ON EXCEPTION | SCREENSHOT, THROWING ERROR|

Check specific folder for screenshot on test failure due to Exception

OUTPUT |FINDING ELEMENTS | FINDELEMENT() & FINDELEMENTS()|

Trying to find: [Element]
Found: '[Element]'.

OUTPUT |CLICK | CLICK()|

Trying to click: '[Element]'
Clicked Element with: '[Element]'

OUTPUT |CHANGING VALUES | CLEAR() & SENDKEYS()|

Changing value in element found [Element] from 'old text' to ''
Changing value in element found [Element] from '' to 'Seleniumworks'

Wednesday, 29 January 2014

Integrate JS with Selenium | Basics

JavaScript make it simpler when Selenium fail to execute certain cases. Here we start with basic exercises using JavascriptExecutor.


1| Alert Msg

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('Hai! This is an Alert msg');");



2| Get Title

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title");
System.out.println("title  : " + title);
OUTPUT | title  : Google 


3| Get Domain name

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String domain = (String) js.executeScript("return document.domain");
System.out.println("domain  : " + domain);
OUTPUT | domain  : www.google.co.in


4| Get URL

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String URL = (String) js.executeScript("return document.URL");
System.out.println("Full URL  : " + URL);
OUTPUT | Full URL  : https://www.google.co.in/


5| Get Attribute | Text

driver.get("http://google.co.in/");
Object exampleDiv = ((JavascriptExecutor) driver).executeScript("return document.getElementById('main');");
String name = ((WebElement) exampleDiv).getAttribute("class");
System.out.println(name);
OUTPUT | content


6| Last Modified

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String lastModified = (String) js.executeScript("return document.lastModified");
System.out.println("lastModified  : " + lastModified);
OUTPUT | lastModified  : 01/29/2014 14:56:46


7| Ready state

driver.get("http://google.co.in/");
JavascriptExecutor js = (JavascriptExecutor) driver;
String readyState = (String) js.executeScript("return document.readyState");
System.out.println("readyState  : " + readyState);
OUTPUT | readyState  : complete


8| Click()

WebElement element = driver.findElement(By.id("Value"));
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
OR |
WebElement element = driver.findElement(By.id("Value"));
trigger("arguments[0].click();", element);

public void trigger(String script, WebElement element) {
((JavascriptExecutor) driver).executeScript(script, element);
}
OR |
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('Value').click()");

Tuesday, 28 January 2014

Capture all the JavaScript Errors | Selenium

Capture js using Firefox profile

1| Download the library file, JSErrorCollector
2| Add to build path.
3| Make use of the library in your code using Firefox profile.

Snippet

import java.util.List;
import net.jsourcerer.webdriver.jserrorcollector.JavaScriptError;
import org.openqa.selenium.firefox.FirefoxProfile;

@BeforeTest
public void setUp() throws Exception {
FirefoxProfile ffProfile = new FirefoxProfile();
JavaScriptError.addExtension(ffProfile);
driver = new FirefoxDriver(ffProfile);
baseUrl = "http://xyz.com";
}

@Test
public void contentTitle() throws Exception {
driver.get(baseUrl + "/");
Thread.sleep(5000);
}

@AfterTest
public void tearDown() throws Exception {
List<JavaScriptError> jsErrors = JavaScriptError.readErrors(driver);
System.out.println("——————START displaying JS errors——————");
for (int i = 0; i < jsErrors.size(); i++) {
System.out.println(jsErrors.get(i).getErrorMessage());
System.out.println("Error in Line: "+ jsErrors.get(i).getLineNumber());
System.out.println(jsErrors.get(i).getSourceName());
System.out.println("\n");
}
System.out.println("——————STOP displaying JS errors———————");
driver.close();
driver.quit();
}





Monday, 27 January 2014

Run Selenium scripts on Cloud - TestingBot | TestNG

Note:  Text in ORANGE can be edited or mentioned important for this entire blog

TestingBot provides similar Browserstack | Saucelabs setup for cloud based automation using Selenium WebDriver.  Given below is a generic test using TestNG from Eclipse IDE that run on TestingBot cloud server. 

1| Log into Testingbot.com
2| Obtain the Client Key and Client Secret from Account.
3| Make use of the following script and do edit whenever necessary.

package packagename;

import java.net.URL;

import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Classname {
private WebDriver driver;

@BeforeClass
public void setUp() throws Exception {
DesiredCapabilities capabillities = DesiredCapabilities.firefox();
capabillities.setCapability("version", "24");
capabillities.setCapability("platform", Platform.WINDOWS);
capabillities.setCapability("name", "Test01");
driver = new RemoteWebDriver(
new URL(
"http://ClientKey:ClientSecret@hub.testingbot.com:4444/wd/hub"),
capabillities);
}

@Test
public void test01() throws Exception {
driver.get("http://www.google.co.in/?gws_rd=cr&ei=zS_mUryqJoeMrQf-yICYCA");
driver.findElement(By.id("gbqfq")).clear();
WebElement element = driver.findElement(By.id("gbqfq"));
element.sendKeys("selenium");
Assert.assertEquals("selenium - Google Search", driver.getTitle());
}

@AfterClass
public void tearDown() throws Exception {
driver.quit();
}
}

4| Got to Tests Tab and get your logs.


TestingBot also lets you run the test through online site.
Follow the steps mentioned below:

1| Open Selenium IDE and record your tests.
2| Save the test suite in HTML format.
3| Log into Testingbot.com
4| Now, try to upload the tests in testingbot site... click on the link.
5| Click 'Choose File' and select already saved html file.
6| Click 'Start a test from scratch'.
7| Name the Test and provide the base URL.
8| Now, select the browser and OS platform.
9| Save settings
10| Click, 'Run this test now'.
11| Go to 'Tests' Tab and get the logs.

Thursday, 16 January 2014

Selenium Data Driven | Properties File

The Properties file lets you store the keywords for data driven tests. Here, the Properties file acts as a data-source; it is used to handle small data files.

1| Open Eclipse IDE
2| Expand the project you are working
3| Right click on the src folder
4| New > Other... > General > File
5| Name the file with extension .properties. e.g., config.properties
6| Copy & paste the following and replace the keywords

search=keyword1,keyword2,keyword3

7| Save the properties file now.

Snippet

import java.util.ResourceBundle;
import java.util.StringTokenizer;

driver = new FirefoxDriver();
baseUrl = "http://xyz.com";

ResourceBundle bundle = ResourceBundle.getBundle("config");
String Channel = bundle.getString("search");
StringTokenizer st = new StringTokenizer(Channel, ",");
while (st.hasMoreTokens()) {
String value = st.nextToken();
driver.get(baseUrl + "/");
driver.findElement(By.id("")).click();
driver.findElement(By.id("")).sendKeys(value);
}


Alternate way to fetch Properties file

#Example1
import java.io.FileInputStream;
import java.util.Properties;

driver = new FirefoxDriver();
driver.get("http://xyz.com/");
FileInputStream fs = new FileInputStream("C:\\config.properties");
Properties prop = new Properties();
prop.load(fs);

String value = prop.getProperty("search");
System.out.println(prop.getProperty("search"));
driver.findElement(By.id("")).click();
driver.findElement(By.id("")).sendKeys(value);


#Example2
import java.io.FileInputStream;
import java.util.Properties;

driver = new FirefoxDriver();
driver.get("http://xyz.com/");
FileInputStream fs = new FileInputStream("C:\\config.properties");
Properties prop = new Properties();
prop.load(fs);

System.out.println(prop.getProperty("path"));
String dd = prop.getProperty("search");
System.out.println(prop.getProperty("search"));
driver.findElement(By.id(prop.getProperty("path"))).click();
driver.findElement(By.id("")).sendKeys(dd);

Let the config.properties File be
path=//*[@id=’clickme’]
search=keyword1

Wednesday, 15 January 2014

TestNG - Verbose Attribute [Selenium Users]

Verbose Attribute lets you obtain clear reports through IDE console. This attribute will be placed inside the <Suite> tag of testng.xml as shown below:

<suite name="Suite" parallel="tests" verbose="2">

There are 10 levels of Verbose, starting from 1 to 10.
verbose="1"  —  verbose="10"

Verbose="10" gives more test details on console output whereas verbose="1" display less details.
Let me explain with an example:



Verbose "1"

1| Open testng.xml make sure verbose="1"


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" verbose="1">
    <test name="Test1">
        <classes>      
            <class name="bundle.Verb"/>
            <class name="bundle.Noun"/>
       </classes>
    </test>
    <test name="Test2">
        <classes>
            <class name="bundle.Adjective"/>      
        </classes>
    </test>

</suite> <!-- Suite -->



2| The IDE console looks like




Verbose "2"

1| Open testng.xml make sure verbose="2"


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" verbose="2">
    <test name="Test1">
        <classes>      
            <class name="bundle.Verb"/>
            <class name="bundle.Noun"/>
       </classes>
    </test>
    <test name="Test2">
        <classes>
            <class name="bundle.Adjective"/>      
        </classes>
    </test>

</suite> <!-- Suite -->



2| The IDE console looks like




Verbose "10"

1| Open testng.xml make sure verbose="10"


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" thread-count="2" verbose="10">
    <test name="Test1">
        <classes>      
            <class name="bundle.Verb"/>
            <class name="bundle.Noun"/>
       </classes>
    </test>

</suite> <!-- Suite -->


2| The IDE console looks like


Tuesday, 7 January 2014

Selenium IDE | Data-driven

This is the continuation of previous post involving advanced concepts of Data-driven tests using Selenium IDE. It helps you while giving a Demo or to do a primary check over the tests again & again. Selenium IDE have an additional feature called user-extensions that gives support to data-driven tests.

Selenium IDE [Data Driven]

1| Download the javaScript files, datadriven.js | goto_sel_ide.js | user-extensions.js from link
2| Open Notepad
3| Copy & Paste following tags and replace the keywords highlighted in Orange with your text.

<testdata>
<test phrase="seleniumworks.com"/>
<test phrase="fire &amp; safety"/>
<test phrase="selenium"/>
<test phrase="Prashanth Sams"/>
</testdata>

4| Save it as a .xml file. e.g., googlesearches.xml
5| Open Selenium IDE.
6| Click Option > Options...
7| Click on Browse under 'Selenium Core extensions (user-extensions.js)'
8| Select all the 3 .js files downloaded earlier [datadriven.js | goto_sel_ide.js | user-extensions.js]
9| Click Ok
10| Restart Selenium IDE








































11| Now, Record the script and edit them in Selenium IDE for proper looping.

loadTestDatafile://c:/googlesearches.xml
while!testdata.EOF()
nextTestData
openhttp://www.google.co.uk
typeq${phrase}
clickbtnG
endWhile
12| Run the Test case

Monday, 6 January 2014

Selenium IDE | Parameterization

Parameterization allows you to do different sets of  permutation & combination; Even it is possible using Selenium IDE.

Selenium IDE [Parameterization]

1| Open Notepad.
2| Copy & Paste the following text with your keywords.

Username = "admin"
Mysecretpass = "pass"

3| Save it as a .js [javascript] file. e.g., Datasource.js
4| Open Selenium IDE.
5| Click Option > Options...
6| Click on Browse under 'Selenium IDE extensions'
7| Select the .js file created [Datasource.js].
8| Click Ok
9| Restart Selenium IDE






































10| Now, Record the script and add the commands highlighted in YELLOW.


























11| Run the Test case

Friday, 3 January 2014

Apache POI for Read & Write | Handling Binary [.xls] Workbook

This is the continuation of previous post. Apache POI also lets you write Excel on test Pass|Fail, etc., I optimized this code using TestNG framework for test Execution.

Write Excel Binary [.xls] Workbook

import java.awt.HeadlessException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class Excelreadwrite {

private static WebDriver driver;
private static String baseUrl;
private static int n = 0;

@BeforeTest
public void setUp() {
driver = new FirefoxDriver();
baseUrl = "https://xyz.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test(dataProvider = "DP")
public static String login(String username, String password)
throws Exception {

driver.get(baseUrl + "/login.v");
String actualtitle = driver.getTitle();
System.out.println(actualtitle);

driver.findElement(By.id("login-username")).sendKeys(username);
driver.findElement(By.id("login-password")).sendKeys(password);
driver.findElement(By.id("login-submit")).click();
Thread.sleep(4000);
driver.findElement(By.id("user-welcome")).click();
driver.findElement(By.id("user-logout")).click();

String expectedtitle = driver.getTitle();
System.out.println("Expected Title is: " + expectedtitle);

int LastRow = ++n;
if (expectedtitle.equals(actualtitle)) {
System.out.println("PASSED");
String status = "PASS";
excelwrite(status, LastRow);
} else {
System.out.println("FAILED");
String status = "FAIL";
excelwrite(status, LastRow);
}

return expectedtitle;

}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

public static void main(String[] args) throws Exception {
excelRead();
}

@DataProvider(name = "DP")
public static String[][] excelRead() throws Exception {
File excel = new File("C:\\Test\\data.xls");
FileInputStream fis = new FileInputStream(excel);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet ws = wb.getSheet("Sheet1");
int rowNum = ws.getLastRowNum() + 1;
  int colNum = ws.getRow(0).getLastCellNum();
  String[][] data = new String[(rowNum - 1)][colNum];
  int k = 0;
  for (int i = 1; i < rowNum; i++) {
  HSSFRow row = ws.getRow(i);
  for (int j = 0; j < colNum; j++) {
  HSSFCell cell = row.getCell(j);
  String value = cellToString(cell);
  data[k][j] = value;
  // System.out.println("The value is" + value);

}
k++;
}
return data;

}

public static void excelwrite(String status, int LastRow) throws Exception {
try {
FileInputStream file = new FileInputStream(new File(
"C:\\Test\\data.xls"));

HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);

Row row = sheet.getRow(LastRow);

Cell cell2 = row.createCell(2); // Shift the cell value depending upon column size
cell2.setCellValue(status);
// System.out.println(status);
file.close();
FileOutputStream outFile = new FileOutputStream(new File(
"C:\\Test\\data.xls"));
workbook.write(outFile);

}

catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (HeadlessException e) {
e.printStackTrace();
}
}

public static String cellToString(HSSFCell cell) {
int type;
Object result;
type = cell.getCellType();
switch (type) {
case 0:
result = cell.getNumericCellValue();
break;
case 1:
result = cell.getStringCellValue();
break;
default:
throw new RuntimeException("There are no support for this type of cell");
}
return result.toString();
}
}








testng.xml

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

Thursday, 2 January 2014

Apache POI for Selenium Data-Driven Tests | Handling Binary [.xls] Workbook

Apache POI lets you manipulate Microsoft documents like .xls and .xlsx; HSSF, Horrible Spread sheet Format implements Excel ’97 (.xls) file format. [I have optimized this framework to work efficient with Selenium]

Handling Binary [.xls] Workbook

import java.io.File;
import java.io.FileInputStream;
import java.util.concurrent.TimeUnit;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class className{
private static WebDriver driver;
private static String baseUrl;

@BeforeTest
public void setUp() {
driver = new FirefoxDriver();
baseUrl = "https://xyz.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test(dataProvider = "DP")
public static int findcount(String username, String password)
throws InterruptedException {
int res = 0;

driver.get(baseUrl + "/login.v");
driver.findElement(By.id("login-username")).sendKeys(username);
driver.findElement(By.id("login-password")).sendKeys(password);
driver.findElement(By.id("login-submit")).click();

return res;
}

@DataProvider(name = "DP")
public static String[][] excelRead() throws Exception {
File excel = new File("C:\\Test\\data.xls");
FileInputStream fis = new FileInputStream(excel);

HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet ws = wb.getSheet("Sheet1");

int rowNum = ws.getLastRowNum() + 1;
int colNum = ws.getRow(0).getLastCellNum();
String[][] data = new String[(rowNum - 1)][colNum];

int k = 0;
for (int i = 1; i < rowNum; i++) {
HSSFRow row = ws.getRow(i);
for (int j = 0; j < colNum; j++) {
HSSFCell cell = row.getCell(j);
String value = cellToString(cell);
data[k][j] = value;
System.out.println("the value is: " + value);
}
k++;
}

return data;
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

public static void main(String[] args) throws Exception {
String[][] data;
data = excelRead();
if (data != null) {
int j = 0;
String aValue = null;
for (int i = 1; i < data.length; i++) {
int pageCount = findcount(data[i][1], data[i][2]); //vary depending upon the Excel columns
if (pageCount > j) {
j = pageCount;
aValue = data[i][1];
}
System.out.println("The count of the data[" + i + "][1] is: "
+ data[i][1] + " = " + pageCount);
}
System.out.println("Greater value: " + aValue + " = " + j);
} else {
System.out.println("No records...");
}
}

public static String cellToString(HSSFCell cell) {

Object result;
switch (cell.getCellType()) {

case Cell.CELL_TYPE_NUMERIC:
result = cell.getNumericCellValue();
break;

case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;

case Cell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;

case Cell.CELL_TYPE_FORMULA:
result = cell.getCellFormula();
break;

default:
throw new RuntimeException("Unknown Cell Type");
}

return result.toString();

}

}






testng.xml

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