How can I stop my code throwing a staleElementReferenceException occasionally, 2/5 runs I will encounter this exception running the same test method, the others it will pass as expected
public boolean checkTextBoxMaxLength(String Textbox, int maxLength) {
int overMaxLength = maxLength + 1;
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < overMaxLength; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
WebElement ele = driver.findElement(By.id(Textbox));
ele = driver.findElement(By.id(Textbox));
String maximum = ele.getAttribute("maxlength");
System.out.println("Element maxlenght is: " +maximum);
ele.sendKeys(output);
String input = ele.getAttribute("value");
System.out.println(input);
System.out.println(output.substring(0,output.length()-1));
if (input.equals(output.substring(0,output.length()-1))) {
return true;
} else {
return false;
}
}
the exception occurs around my WebElement ele. Sometimes the exception occurs at:
ele = driver.findElement(By.id(Textbox));
(the reason I am reassigning ele is because if I don't the exception will occur at the line declaring WebElement ele, and sometimes it will occur here:
ele.sendKeys(output);
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
Resetting my element before the exception does not seem to help either.
ele = driver.findElement(By.id(Textbox));
String maximum = ele.getAttribute("maxlength");
System.out.println("Element maxlenght is: " +maximum);
My exception is still thrown here @ line 2