Uziii
Uziii

Reputation: 841

Debugging StaleElementReference exception - Selenium WebDriver

I am in some kind of situation here.

I have a function editNewUser().

public void editNewUser() throws Exception
    {
        driver.findElement(adminModuleDD).click();
        wait.until(ExpectedConditions.visibilityOfElementLocated(searchRes));
        List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(uNames));
        for(WebElement el : elements)
        {
            if(el.getText().equals(UserName))
            {
                el.click();
                wait.until(ExpectedConditions.visibilityOfElementLocated(editUserHeading));
                driver.findElement(editUser).click();
                WebElement status_Dropdown = driver.findElement(By.xpath("//select[@id='systemUser_status']"));
                Select status = new Select(status_Dropdown);
                status.selectByVisibleText("Enabled");
            }
        }   
    }

The UserName is a public string variable that gets value in another function, during creation of user.

In this script, I am navigating to a page that contains list of users, I am storing all user names in List 'elements' and then iterating over each element in the list whose text matches with user name.

Now, in my test_run script, I have some other methods calling after editNewUser().

The thing happens is, this method executes the following commands in if block.

if(el.getText().equals(UserName))
    {
        el.click();
        wait.until(ExpectedConditions.visibilityOfElementLocated(editUserHeading));
        driver.findElement(editUser).click();
        WebElement status_Dropdown = driver.findElement(By.xpath("//select[@id='systemUser_status']"));
        Select status = new Select(status_Dropdown);
        status.selectByVisibleText("Enabled");
    }

But as soon as next method is called, it stops the execution and throws org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up

Stack Trace refers to the line if(el.getText().equals(UserName)).

Can you tell me why am I receiving this exception, event though the commands inside if block are executed.

Upvotes: 0

Views: 203

Answers (1)

Breaks Software
Breaks Software

Reputation: 1761

The error message is telling you the problem. The page has changed once you edit the first "el" in your for loop, the page has been updated, so Selenium has lost track of the remaining elements in the "elements" list.

You'll need to find another way to track the elements that you are looping through. a technique that I've used in the past is create a custom object to represent the items, in your case perhaps "User". that object is then smart enough that it can re-find itself on the page.

Upvotes: 0

Related Questions