Before the completion of the initial test, the second selenium test has already been initiated

I am facing an issue while running two Selenium tests sequentially. I have implemented waiters in the tests to wait for elements to become visible before interacting with them. Sometimes, the second test starts executing while the first test is still waiting for an element to load.

Below is the code for the waiter:

public void waitElementIsVisible(String locator) {
    logger.info("Waiting for element with locator " + locator + " to load in " + driver.getCurrentUrl() + " page");
    WebDriverWait wait = new WebDriverWait(driver, 15, 100);
    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(locator)));
}

This method utilizes the waiter:

protected void clickJs(String locator){
    waiters.waitElementIsVisible(locator);
    JavascriptExecutor js = (JavascriptExecutor) driver;
    WebElement el = findPageElementByXpath(locator);
    js.executeScript("arguments[0].click();", el);
}

The following method uses the JavaScript click function mentioned above:

public ActivitiesPage goToActivitiesPage(){
    clickJs(activitiesPage);
    return new ActivitiesPage();
}

And here are the two test methods:

@Test
public void doSuccessfulLoginTest(){
    LoginPage page = new LoginPage();
    page.doSuccessfulLogin("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="234a51160c1042410812474613214e424a4f583b46241f18">[email protected]</a>", "qwerty").
    goToActivitiesPage(). 
            goToSignUpFormsPage().
    clickCreateSignupFormButton().
    specifySignUpFormName(Helper.getCurrentDateAndTime()).
    clickNextButton().
    selectLayout().
    clickNextButton().
    clickNextButton().
    clickNextButton(); 

    try {
        System.out.println("assertions");
        Assert.assertEquals(getDriver().getCurrentUrl().contains("dashboard"), true);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Test
public void doSuccessfulLoginTestAndPublishSignupForm(){
    ActivitiesPage ap = new ActivitiesPage();
    ap.goToSignUpFormsPage().
    clickCreateSignupFormButton().
    specifySignUpFormName(Helper.getCurrentDateAndTime()).
    clickNextButton().
    selectLayout().
    clickNextButton().
    clickNextButton().
    clickNextButton(); 

    try {
        System.out.println("assertions");
        Assert.assertEquals(getDriver().getCurrentUrl().contains("subscribe"), true);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

If an element is being waited for inside the goToActivitiesPage() method of the first test, the second test will start executing prematurely.

How can I ensure that the first test completes before the second one begins?

Answer №1

Imagine you have divided your methods into separate tests annotated with @Test in Selenium. If these are considered as 2 selenium tests, the only way this could happen is if the tests are set to run in parallel. Otherwise, they will always execute sequentially. To investigate any failures, refer to the test report for clues. If using TestNG, you can easily resolve this by utilizing a helpful feature known as dependsOnMethods (Ex.

@Test
public void test1() {}

@Test(dependsOnMethods = {"test1"}) //test2 will wait until test1 is finished
public void test2() {}

Pro Tip for debugging: By default, tests run sequentially unless specifically configured otherwise. Always check the test report for insights into any failure reasons.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with Dropdown Boxes and Alert Messages in Selenium

I have been struggling with two issues that I cannot seem to resolve no matter what I try. Seeking assistance from the community for help. Problem 1: During execution, alerts keep popping up which halts the program. How can I handle these interruptions wi ...

Working with C# and Selenium can sometimes lead to issues with elements not being

I've been working on automating a UI test using selenium in c#. Take a look at my code: driver = new ChromeDriver(); driver.Manage().Window.Maximize(); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30)); driver.Navigat ...

Strategies for handling atypical issues in Selenium 2.0

As a beginner in selenium2.0, I ask you seasoned heroes for advice on how to throw exceptions when encountering web page errors. How can selenium2.0 capture and handle these exceptions effectively? I don't want the testing process to come to a halt d ...

Error message: org.apache.jorphan.util.JMeterException: Unable to execute bsh method: evalSourced script: inline evaluation of:

After upgrading from selenium-server-standalone-2.53.0 to selenium-server-standalone-3.1.0 in the %Jmeter%lib folder, I encountered the following error: Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced fil ...

A guide to pasting copied text from the clipboard using Selenium and Java on a Mac operating system

Having trouble pasting text into a textbox on MACOS? Trying to use the code snippet below, but Control + v and Command + v shortcuts are not working. It seems like this is a known issue, but unsure if it has been resolved yet. https://github.com/seleniumhq ...

Leveraging selenium for automating client interactions by enabling camera functionality

As I develop a WebRTC application, the permission to use the camera prompt appears. While I understand that it is not possible to remove this prompt, I am wondering if there is a way to automate the clicking of the allow button on the client's side us ...

Is it possible to modify the rows and columns of a password-protected Excel spreadsheet using Java programming?

NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("C://Users//RK5026051//Downloads//500_Lanes.xls")); EncryptionInfo info = new EncryptionInfo(fs); Decryptor d = Decryptor.getInstance(info); if (d.verifyPassword("manh.com")) { ...

The IWebElement Text Property now includes support for displaying emojis

OpenQA.Selenium.IWebElement.Text When accessing the Text Property and the HTML inner text is ":x:", you will receive ":x:". If the Text is ":white_check_mark:", the Return Value will be ":white_check_mark:". I searched for various Emojis and Unicode Ref ...

Having trouble finding a webpage element (button) with the ID 'next' using Python and Selenium

I recently delved into Python with Selenium to automate tasks, but I've hit a roadblock. My goal is to create a script that automatically clicks the 'next' button on a webpage. However, I'm facing difficulty in locating the element (but ...

Getting the href values of dynamically changing links with Selenium in Python: A step-by-step guide

Is there a way to extract all hrefs(links) located in anchor tags using JavaScript code with Selenium Python, especially when these links are dynamically updated? The tag I am trying to click on is as follows: enter image description here I have managed t ...

Pressing the button immediately after filling the Box with a 6-digit number

Currently, I am using Selenium and faced a situation where I have to click on a button immediately after entering a six-digit number in a text field. Does anyone have any suggestions on how to accomplish this? I'm still relatively new to Selenium, so ...

tips for extracting the src attribute of multiple LinkedIn profiles with selenium

Python code sign_in_button1=driver.find_element_by_xpath('''/html/body/div[8]/div[3]/div/div/div/div/div[2]/main/div[1]/section/div[2]/div[1]/div[1]/div/div/img''') src = sign_in_button1.get_attribute('src') pri ...

Obtain the HTML document using C# Selenium once it has been altered

My current HTML source looks like this: <b class="number"> Click to see </b> After clicking on the above element, the corresponding JS code is executed: function fun(){ number.html("12345"); } Although utilizing driver. ...

Is there a way to confirm the alignment of dropdown selections with the user interface choices in Selenium WebDriver with Java?

I've managed to create code that reads options from a property file, but I'm unsure how to verify if the same value exists in the UI drop-down. If anyone could assist me with this code: @Test() public void Filterselection_1() throws Exception{ ...

How to extract HTML elements using Selenium WebDriver

Attempting to send an email using HTML and CSS through Selenium has proven challenging. It seems that Selenium is only able to retrieve the text or code of the page, but not the actual page itself. Is there a way to duplicate the entire page? Methods Trie ...

Unable to include JUnit 5 Test Case

Currently, I am in the process of setting up a new project on my colleague's PC within Eclipse. This project involves the use of Selenium, JUnit 5.4, and Maven. However, we have encountered an issue where the option for New JUnit Juniper Test does not ...

Unable to perform file upload using SendKeys method in Selenium

I'm struggling with an issue related to uploading files in Selenium using C# .NET with FirefoxDriver. Here's the code I have: IWebElement chooseFile = driver.FindElement(By.XPath("//button[@id='btnSelect']")); chooseFile.SendKeys(@"D:&b ...

python code unable to execute selenium script

Attempted to run the following code: from selenium import webdriver browser=webdriver.Chrome() browser.get('http://www.google.com') However, it fails to execute and displays an error message: =RESTART: C:\Users\Phani\AppData&b ...

Python script is not launching Electron and Vuejs application using selenium for end-to-end testing

I need assistance with conducting end-to-end testing for an Electron app using Selenium and Python. To set up a sample app in Electron and Vue.js: npm install electron --save-dev npm install -g @vue/cli vue create new-app vue add electron-builder To ...

What is the best way to choose (or activate) a button within a table?

Is there a way to target the button in the first row of this table? <table id="comms-table" class="table table-condensed"> <tbody> <tr><th class="bordered" style="text-align: center;" width="50">Status</th>& ...