Earlier we saw how to write down data driven test cases using Excel file. Using Excel for data driven has it's own advatages like you can write down you function in excel and get rid of programming logic from your test. However to connect to excel you need JDBC connectivity which has it's own overhead in terms of processing time and you always need to remember to close the connection.
In a way using CSV for selenium automation is much faster than Excel. so let's see how to use CVS file with selenium automation.
Save the following data as data.csv. First row is header
Scenario name,username,password
valid,Gaurang,Shah
invalid,Gaurang,ccc
In a way using CSV for selenium automation is much faster than Excel. so let's see how to use CVS file with selenium automation.
Save the following data as data.csv. First row is header
Scenario name,username,password
valid,Gaurang,Shah
invalid,Gaurang,ccc
import java.io.BufferedReader; import java.io.FileReader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * @author GauranG Shah */ public class ReadCSV { /** * * @param scenarioName - Row Name * @param columnName * @param fileName - CSV file name where data is stored * @return - Sting value */ public String getValue(String scenarioName, String columnName,String fileName){ try { // csv file containing data String strFile = fileName; String strLine = ""; StringTokenizer st = null; int lineNumber = 0; // create BufferedReader to read csv file BufferedReader br = new BufferedReader(new FileReader(strFile)); strLine = br.readLine(); //read first line st = new StringTokenizer(strLine, ","); int totalRows = st.countTokens(); Map<Object,String> mp=new HashMap<Object, String>(); //Fetch the header for(int row=0; row<totalRows; row++){ mp.put(new Integer(row), st.nextToken()); } lineNumber++; while ((strLine = br.readLine()) != null){ st = new StringTokenizer(strLine, ","); lineNumber++; if(st.nextToken().equalsIgnoreCase(scenarioName)){ //Identified the row Now return the specific element based on column name specified. totalRows= st.countTokens(); for(int key=1; key<=totalRows; key++){ String value = st.nextToken(); if(mp.get(key).equalsIgnoreCase(columnName)){ return value; } } } } }catch (Exception e){ System.out.println("Exception while reading csv file: " + e); } return "Element Not Found"; } //This is just to show usage, you can discard this when you use in your project public static void main(String[] args) { ReadCSV rc = new ReadCSV(); System.out.println(rc.getValue("valid", "username","data.csv")); } }
2 comments:
where are you calling the csv file in the above code?
How should I run this file? I am nooby. Can you please explain
Post a Comment