Saturday, March 1, 2014

Using Configuration (Config File) While Test Automation.

It is always advised to use a config file in your test automation. The purpose of having a config file is to have few variables outside of code so that if you can change variables' values without changing your code.

To use a config file in Java, Apache's common configuration jar is very popular and easy to use.

Download the latest version of these jar and add them to Project's Build Path.
commons-lang-2.6.jar
commons-configuration-1.10.jar

Here is the sample code to read config:

public static void InitializeConfiguration()  
{
        PropertiesConfiguration propertyConfigFile;
try
{
propertyConfigFile = new PropertiesConfiguration();
String config = "/config/config.txt"; //Location of config file
propertyConfigFile.load(config);

        //Read variable from config 
        String url = propertyConfigFile.getProperty("qaURL").toString();
}
catch(ConfigurationException e)
{
System.out.println("Error Occured While Reading Config File");
}

}

Copy the below line in a notepad and save it with some valid extension. qaURL is the variable being called in above program. This will serve the purpose of a config file.
## is used to comment the line.

Sample:

## Please provide the URL here:
qaURL = https://www.google.com





Reading and Writing Excel Sheet

Reading and Writing Excel Sheets:

While automating your tests using selenium, its quiet frequent to use excel sheet as Object Repository or test data sheet or may be a result sheet.
Here I am gonna tell you some ways to read / write excel sheet in Java for Selenium Web Driver.

There are various third party libs are available to handle excel operations, popular ones are POI and JXL.

Writing an Excel File Using JXL: 

Before you start using JXL, you need to download the latest version of jxl.jar and attach it to Java Build Path of your project.

ixl can be downloaded from http://www.quicklyjava.com/jexcel-jar-download/

This is sample code to write a 2 D Array in an excel sheet.


Few Points to remember while writing an excel sheet:

1. Always use sheet.addCell(string) method to write the contents in excel sheet.
2. Always remember to close the workbook after writing.
3. Always use Exception Handling and use these book.write(); book.close(); in Finally block so that even if there is any exception and code exception is broken then at least the previous data till exception is written in excel sheet otherwise there won't be any data in excel sheet.





Reading an Excel File Using JXL: 

Sample code to read an existing excel sheet: