Selenium-FileHandeling - Notes By ShariqSP
Selenium with Properties Files and Excel File and JSON File
Importance of File Programming in Selenium:
File programming in Selenium is essential for various reasons:
- Data-driven Testing
- Configuration Management
- Enhanced Readability
using Properties Files in Selenium
What is a Properties File and its Syntax:
A properties file is a simple text file with key-value pairs separated by an equals sign (=).
username=admin
password=secretpassword
url=https://example.com
Why We Need Properties File:
Properties files provide flexibility in managing configuration settings and test data separately from the code, enhancing maintainability and allowing easy modification.
How to Use Properties File in Selenium with Java:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class SeleniumWithPropertiesFile {
public static void main(String[] args) {
Properties prop = new Properties();
try {
// Load properties file
prop.load(new FileInputStream("config.properties"));
// Retrieve values from properties file
String browser = prop.getProperty("browser");
String url = prop.getProperty("url");
// Print values
System.out.println("Browser: " + browser);
System.out.println("URL: " + url);
// Now you can use these values in your Selenium code
// Example:
// WebDriver driver = new ChromeDriver();
// driver.get(url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this code:
Properties
: Represents a persistent set of properties. It is used to load properties from the file and retrieve values by keys.FileInputStream
: Reads input bytes from a file. In this case, it's used to read the properties file (config.properties
).load(InputStream in)
: Reads a property list from the specified input stream. This method loads properties from the file into theProperties
object.getProperty(String key)
: Searches for the property with the specified key in the properties list. It returns the value associated with the key.
This Java code demonstrates how to load values from a properties file (config.properties
) and use them in your Selenium automation script.
Using Excel Files in Selenium:
Excel files are commonly used in Selenium automation testing for storing test data in a structured manner. Utilizing Excel files offers several advantages:
- Structured Data Storage: Excel files allow you to organize test data into rows and columns, providing a structured format for storing various test inputs.
- Flexibility: Excel files support multiple sheets, which can be useful for categorizing test data based on different scenarios or test cases.
- Integration with External Tools: Excel files can be easily integrated with external tools and frameworks for data manipulation, analysis, and reporting.
When using Excel files in Selenium, libraries such as Apache POI (Poor Obfuscation Implementation) are commonly employed to read and write data from Excel files.
Apache POI Library:
Apache POI is a popular Java library that provides APIs for working with Microsoft Office formats, including Excel files. It allows Selenium scripts to read data from Excel files and interact with them programmatically.
How to Use Excel Files in Selenium:
Below is an example demonstrating how to use Apache POI to read data from an Excel file in a Selenium automation script:
Before we start with program first download the latest jar files from here and configure all jar files in buildpath
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class SeleniumWithExcel {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("testdata.xlsx");
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheet("Sheet1");
// Iterate through each row in the sheet
for (Row row : sheet) {
// Iterate through each cell in the row
for (Cell cell : row) {
// Extract data from cell
String cellValue = cell.getStringCellValue();
System.out.print(cellValue + "\t");
}
System.out.println(); // Move to the next line
}
workbook.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example:
Workbook
: Represents the Excel workbook. In this case, we are using anXSSFWorkbook
for reading Excel files in the XLSX format.Sheet
: Represents an Excel worksheet. We obtain the desired sheet usingworkbook.getSheet("Sheet1")
.Row
andCell
: Represent rows and cells within the worksheet, respectively. We iterate through each row and cell to extract data usinggetStringCellValue()
.
Using JSON Files in Selenium:
JSON (JavaScript Object Notation) files are commonly used in Selenium automation testing for storing and exchanging structured data between different systems. Utilizing JSON files offers several advantages:
- Structured Data Representation: JSON provides a lightweight and human-readable format for representing structured data, making it easy to manage and understand.
- Interoperability: JSON files can be easily exchanged between different programming languages and platforms, facilitating seamless integration with Selenium scripts and other systems.
- Flexibility: JSON supports complex data structures such as arrays and nested objects, allowing you to represent diverse test data scenarios.
How to Use JSON Files in Selenium:
Below is an example demonstrating how to use JSON files in a Selenium automation script:
/**
*
* @param Path : enter the path to json object file
* @param key : enter the key you want to retrieve
* @return value in String format
* @throws ParseException
* @throws FileNotFoundException
* @throws IOException
*/
public static String readFromJsonFile(String Path,String key) throws ParseException, FileNotFoundException, IOException
{
// parsing file "JSONExample.json"
Object obj = new JSONParser().parse(new FileReader(Path));
// typecasting obj to JSONObject
JSONObject jo = (JSONObject) obj;
// getting firstName and lastName
String name = (String) jo.get("name");
return name;
}
com.google.code.gson
gson
2.8.9
com.googlecode.json-simple
json-simple
1.1.1
In this example:
JSONParser
: Parses JSON text into a JSON object model.JSONObject
: Represents a JSON object. We extract data from this object usingget()
method.FileReader
: Reads text from character files. We use it to read the contents of the JSON file.
Examples
Using properties file
firstpro.properties
No.7 : Dhoni
No.10 : sachin
java Program
public static void main(String[] args) throws IOException {
File f = new File("./TestData/firstpro.properties");
FileInputStream fis = new FileInputStream(f);
Properties pro = new Properties();
pro.load(fis);
System.out.println(pro.get("No.7"));
System.out.println(pro.getProperty("No.10"));
}
Using properties Excel File
EXcel Doc
Java Program
public static void main(String[] args) throws EncryptedDocumentException, IOException {
File f = new File("./TestData/demo.xlsx");
FileInputStream fis = new FileInputStream(f);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet("Sheet1");
//fetch single cell
String cellData = sheet.getRow(0).getCell(0).toString();
System.out.println(cellData);
//fetch entire row
//first read total no of rows
int rowNO=sheet.getPhysicalNumberOfRows();
int colNo=sheet.getRow(0).getPhysicalNumberOfCells();
for(int i=0;i < rowNO;i++)
{
for(int j=0;j < colNo;j++)
{
System.out.print(sheet.getRow(i).getCell(j).toString()+" ");
}
System.out.println();
}
}
Data Utility Class
A Data Utility Class is a Java class containing methods for handling various utility functions related to data processing. These methods can be used to perform common operations such as data retrieval, data manipulation, and data validation.
Why do we need Data Utility Class?
Data Utility Classes are useful for encapsulating data-related functionalities in one place, promoting code organization, reusability, and maintainability. They provide a modular approach to handle data operations, making the code cleaner and easier to manage.
Use Cases
Selenium Automation
Data Utility Classes can be handy in Selenium automation for tasks such as reading data from property files to configure test parameters or extracting data from Excel files to use as test data.
Property File
The propertyFileGetValue
method in the DataUtilityClass
reads a specific key's value from a property file. This is useful for retrieving configuration settings or test parameters stored in a property file.
Excel File
The getCellFromExcel
, getColValues
, getRowValues
, and getFullSheet
methods in the DataUtilityClass
extract data from Excel files. These methods allow fetching individual cells, entire columns, entire rows, or the entire sheet from an Excel file, which can be used as test data in Selenium automation.
Explanation of Methods
propertyFileGetValue(String path, String key)
: Retrieves a value associated with a given key from a property file.getCellFromExcel(String path, String sheetName, int colNum, int rowNum)
: Retrieves the value of a cell from an Excel file specified by its row and column indices.getColValues(String path, String sheetName, int colNum)
: Retrieves all values in a specified column from an Excel sheet.getRowValues(String path, String sheetName, int rowNum)
: Retrieves all values in a specified row from an Excel sheet.getFullSheet(String path, String sheetName)
: Retrieves all values from an entire Excel sheet.
Java Program Example
public class DataUtilityClass {
public static String propertyFileGetValue(String path, String key) throws IOException {
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
Properties pro = new Properties();
pro.load(fis);
return (String) pro.get(key);
}
public static String getCellFromExcel(String path, String sheetName, int colNum, int rowNum)
throws EncryptedDocumentException, IOException {
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
String cellData = sheet.getRow(0).getCell(0).toString();
return cellData;
}
public static String[] getColValues(String path, String sheetName, int colNum)
throws EncryptedDocumentException, IOException {
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
int rowNO = sheet.getPhysicalNumberOfRows();
String[] colValues = new String[rowNO];
for (int i = 0; i < rowNO; i++) {
colValues[i] = sheet.getRow(i).getCell(colNum).toString();
}
return colValues;
}
public static String[] getRowValues(String path, String sheetName, int rowNum)
throws EncryptedDocumentException, IOException {
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
int colNo = sheet.getRow(0).getPhysicalNumberOfCells();
String[] colValues = new String[colNo];
for (int i = 0; i < colNo; i++) {
colValues[i] = sheet.getRow(rowNum).getCell(i).toString();
}
return colValues;
}
public static String[][] getFullSheet(String path, String sheetName)
throws EncryptedDocumentException, IOException {
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheet(sheetName);
int rowNO = sheet.getPhysicalNumberOfRows();
int colNo = sheet.getRow(0).getPhysicalNumberOfCells();
String[][] sheetValues = new String[rowNO][colNo];
for (int i = 0; i < rowNO; i++) {
for (int j = 0; j < colNo; j++) {
sheetValues[i][j] = sheet.getRow(i).getCell(j).toString();
}
System.out.println();
}
return sheetValues;
}
}
File Reading Interview Questions
- Why is it important to read files in Selenium WebDriver tests?
- What are some common types of files that you might need to read in Selenium WebDriver tests?
- How do you read a property file in Selenium WebDriver?
- What are the advantages of using property files for test data?
- Explain the process of reading an Excel file in Selenium WebDriver.
- What are some libraries available in Java for reading Excel files?
- How do you read data from specific cells in an Excel file using Apache POI?
- How do you handle different types of data (numeric, string, boolean) when reading from an Excel file?
- What are some common challenges you might encounter when reading Excel files in Selenium WebDriver tests?
- How do you read data from a JSON file in Selenium WebDriver?
- What are the advantages of using JSON files for test data?
- Explain the process of reading JSON data using libraries like Gson or Jackson in Selenium WebDriver.
- How do you handle nested JSON objects when reading from a JSON file?
- How do you read data from arrays within a JSON file?
- What are some common methods for parsing JSON data in Selenium WebDriver?
- How do you handle exceptions when reading files in Selenium WebDriver?
- What are some best practices for managing and organizing file reading code in Selenium WebDriver tests?
- How do you ensure the reliability and accuracy of data read from files in Selenium WebDriver tests?
- How do you validate the data read from files in Selenium WebDriver tests?
- How do you handle file path management and configuration in Selenium WebDriver tests?
Multiple Choice Questions (MCQs)
- Which type of file is commonly used for storing key-value pairs in Selenium WebDriver tests?
- Property file
- Excel file
- JSON file
- Text file
- Which library is commonly used for reading Excel files in Selenium WebDriver tests?
- Apache POI
- Jackson
- Gson
- JsonPath
- Which library is commonly used for reading JSON files in Selenium WebDriver tests?
- Gson
- Apache POI
- Jackson
- JsonPath
- Which method is used to read data from a property file in Selenium WebDriver?
- getProperty()
- readProperty()
- get()
- read()
- Which method is used to read data from a specific cell in an Excel file using Apache POI?
- getCellData()
- readCell()
- getCell()
- getCellValue()
- Which method is used to read JSON data from a file using Gson library?
- fromJson()
- parse()
- readJson()
- load()
- What is the advantage of using JSON files for test data?
- JSON files are human-readable and easy to write
- JSON files provide better support for nested data structures
- JSON files have built-in support for comments
- All of the above
- Which method is commonly used for parsing JSON data in Selenium WebDriver?
- parse()
- fromJson()
- readJson()
- load()
- How do you handle exceptions when reading files in Selenium WebDriver?
- Using try-catch blocks
- Using assert statements
- Ignoring exceptions
- All of the above
- How do you validate the data read from files in Selenium WebDriver tests?
- Using assert statements
- Manually inspecting the data
- Ignoring validation
- All of the above