Question about handling random "no such element" exception in WebDriver Java

  • So here's the setup, we have tests where we fetch test data from excel sheet and iterate over all the rows within a particular test. So, for example, there are tests that create some user profiles, once they do; there's a success message that appears on the next page, our test uses the "findElement.." method to capture that element and get's the text to verify that 1) it appears and 2) that the message is correct. Now here's the problem, since the test may iterate over and over a lot (because of excel data rows), every so often we notice that the test throws NoSuchElementException while looking for that success message. I was recently told by someone that instantiating that page object class at each iteration would solve this issue. So my main question really is that would instantiating the page object class solve this, or is there something else I'm missing? Following is a sample of the code (not exact code of course)

        SuccessPage successPage = new SuccessPage(driver);
        InputPage inputPage = new InputPage(driver);
        String successMessage = "";
        excelSheetData = someCustomMethodThatFetchesDataFromExcel();
        for (Map<String, String> rows : excelsheetData){
          successMessage = successPage.successEle.getText();
          Assert.assertEquals(expectedSuccessMessage, successMessage);

    Page object file look something like this

        public class SuccessPage {
        WebDriver driver;
           public SuccessPage(WebDriver driver){
              this.driver = driver;
        public WebElement someElement;

    So roughly about 8 out of 10 times the above code works correctly, but those two other times it throws that NoSuchElementException at successMessage = successEle.getText(); What I've been told I should do instead is something like the following

        SuccessPage successPage;
          //create a wrapper clickSubmitBtn() method that returns the page object.
          successPage = inputPage.clickSubmitBtn(driver); //this will instantiate the page object.
          successMessage = successpage.successEle.getText();
          ... }


    1. will this really solve the problem?
    2. is that a good programming practice, should instantiation be done once before the loop?

  • Taking your questions in order:

    1. I do not think, changing the structure of your code is going to resolve the issue. In most cases where the tests fail intermittently, the problem will be with some timing issue. Something like the click is not registering. Check your browser console for any errors in the javascript. Try adding some delay after sendKeys().

    2. Most good programming practices are suggestions - without looking at the whole structure it will not be possible to give them :).

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2