How to import a CSV and use it as variables in java

Viewed 214

I have a CSV file of two columns an IP and password . this is my code but it's not working any help would be great sorry for any mistakes , first time here . note that everything works fine inside the page , only the CSV part that I'm missing

public class DataDrivenTestingUsingCSVInSelenium {
 
//Provide test data CSV file path. As below path based on Mac machine. So, lets say you are using windows machine then write the below path accordingly. 
String CSV_PATH = "C:\\Users\\SAAD\\Desktop\\Cam. Inventory.csv.csv";
WebDriver driver;
private CSVReader csvReader;
String[] csvCell;

public void setup() throws Exception {
    
    System.setProperty("webdriver.ie.driver","C:\\Users\\SAAD\\Downloads\\IEDriverServer_Win32_4.0.0\\IEDriverServer.exe");
    WebDriver driver = new InternetExplorerDriver();
    
}
public void dataRead_CSV() throws IOException, CsvValidationException {
    //Create an object of CSVReader
    Actions hold = new Actions(driver);
    csvReader = new CSVReader(new FileReader(CSV_PATH));
    String pass = csvCell[1];
    String ip = csvCell[0];
    driver.get("http://"+ ip +"/doc/page/config.asp");
    driver.manage().window().maximize();
    WebElement Username = driver.findElement(By.id("username"));
    Username.click();
    Username.sendKeys("admin");
    WebElement Password = driver.findElement(By.id("password"));
    Password.click();
    Password.sendKeys(pass);
    Password.sendKeys(Keys.RETURN);

    
    
    

    
    
}
}

any suggestions would be great , thanks in advance .

1 Answers

The issue is that you are just declaring the String[] csvCell; but you are not initializing it. In your code you are interrogating, String pass = csvCell[1]; it - but the array is null.

Let's say you have two columns - IP and Pass. Using your way of writing the code, here is the updated one.

public void dataRead_CSV() throws IOException, CsvValidationException {
    Actions hold = new Actions(driver);
    csvReader = new CSVReader(new FileReader(CSV_PATH));

    csvReader.readHeaders();
    String pass = csvReader.get("Pass");
    String ip = csvReader.get("IP");

    driver.get("http://"+ ip +"/doc/page/config.asp");
    driver.manage().window().maximize();
    WebElement Username = driver.findElement(By.id("username"));
    Username.click();
    Username.sendKeys("admin");
    WebElement Password = driver.findElement(By.id("password"));
    Password.click();
    Password.sendKeys(pass);
    Password.sendKeys(Keys.RETURN);
}

And you can delete the csvCell variable.

Related