-1

How can I retrieve the next value from text file when there is a failure in the test case?

Here is my code:

public void openFile(){
  try{
    x = new Scanner(new File("C:\\Project1\\ids.txt"));
    public void readFile(){
    }
  }catch(Exception e){
    System.out.println("not find file");
  }
  while(x.hasNext()){
    String a = x.next();
    driver.findElement(By.xpath("//*[@id=\"in_member_id\"]")).sendKeys(a);
  }
}

If the value in line number 1 of file ids.text is wrong I want it to put the second value then the third and so on. If it's right I want it to continue to the last of the file.

Stefan Crain
  • 2,010
  • 3
  • 21
  • 22

1 Answers1

0

One strategy you could try if your file isn't unreasonably large is to pre-fetch all the lines and store them in a list. Then loop over and break as the final statement which symbolizes the success that means you can stop trying. That could look something like this:

// Let's just assume the file is always found for example's sake
Scanner in = new Scanner(new File("C:\\Project1\\ids.txt"));
List<String> fileLines = new ArrayList<>();

// Pre fetch all the lines in the file
while (in.hasNextLine()) {
    String line = in.nextLine();
    if (!line.isEmpty()) {
        fileLines.add(line);
    }
}

// Try each id until one succeeds and the loop is broken
for (String aLine : fileLines) {
    try {
        driver.findElement(By.xpath("//*[@id=\"in_member_id\"]")).sendKeys(a);

        // Here is where you would check for failures that don't throw an exception, if you need to...

        // If this break is reached, then no failures were detected
        break;

    // If a failure happens that results in an exception
    } catch (Exception e) {
        System.out.println("An error happened, trying next line");
    } 
}
Julian
  • 1,665
  • 2
  • 15
  • 33