LambdaTest Community

Find answers, support, and inspiration from other users

Questions
LambdaTest Community
Answered

How can a Selenium 4 relative locator change the way you perform automation testing?

Can anyone please tell me how can a Selenium 4 relative locator change the way you perform automation testing.

Up Vote Down Vote 0 Votes
Posted 3 months ago

Answers


Yep!! you heard it right. Selenium 4 will bring out a new Locator that has been in plans for quite some time now called Relative Locator.

As of now, Selenium 4 relative locator methods support usage with withTagName attribute. Following are the ‘relative locator’ options that can be used in Selenium automation testing:

RELATIVE LOCATOR- DESCRIPTION

1. above - Web element to be searched/located appears above the specified element.

2. below - Web element to be searched/located appears below the specified element.

3. toLeftOf - Web element to be searched/located appears to the left of the specified element.

4. toRightOf - Web element to be searched/located appears to the right of the specified element.

5. near - Web element to be searched/located is at most 50 pixels away from the specified element.

Here is a screenshot of the implementation that highlights the usage of relative locators in Selenium automation testing (Source (SeleniumHQ/selenium)).

If you are wondering about how Selenium does it, well, it does so with the help of a JavaScript method called getBoundingClientRect(). This JavaScript method allows Selenium to locate the elements using the relative locators for Selenium testing.

Execute Selenium Automation Testing With Relative Locator

Let’s get into the action with the new Selenium 4 Relative Locator to perform automated cross browser testing. I am going to perform a trial run of Selenium 4 (Alpha) along with the local Chrome WebDriver. But before that, I am going to create a Maven project for implementation and testing. I will be using the TestNG framework as it can be easily integrated with Maven. Also, because of the built-in annotations (e.g. @BeforeClass, @AfterClass, @Test, etc.) that offers more clarity on the automation tests being triggered.

For both the tests that will be demonstrated further, the Project Object Model (pom.xml) file for the Maven project should be updated with the project configuration [including Selenium 4(Alpha)].

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Group-Name</groupId>
  <artifactId>Artifact-Name</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>10</source>
                    <target>10</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.0.0-alpha-3</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.0.0</version>
            <scope>compile</scope>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.28</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Example 1: For Selenium 4 Relative Locators

In the first example that demonstrates the usage of Selenium 4 relative locators, the intent is to automate the login to LambdaTest (Free Cross Browser Testing Tool on Cloud - LambdaTest). As the test is performed on the Chrome browser, you should ensure that the Chrome WebDriver is available on the machine.

import io.github.bonigarcia.wdm.WebDriverManager;
import http://org.openqa.selenium.By (http://org.openqa.selenium.By) (http://org.openqa.selenium.By (http://org.openqa.selenium.By));
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.openqa.selenium.support.locators.RelativeLocator.withTagName;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import http://java.net (http://java.net) (http://java.net).MalformedURLException (http://java.net).MalformedURLException);
import http://java.net (http://java.net) (http://java.net).URL (http://java.net).URL);
import java.util.concurrent.TimeUnit;
public class MavenRelocators {
private WebDriver driver;
boolean status = false;
@BeforeClass
public void setUp(){
System.setProperty("webdriver.chrome.driver","C:\\location-of-chromedriver.exe");
driver = new ChromeDriver();
driver.get("Free Cross Browser Testing Tool on Cloud - LambdaTest (https://accounts.lambdatest.com/login) (Free Cross Browser Testing Tool on Cloud - LambdaTest (https://accounts.lambdatest.com/login))");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@AfterClass
public void tearDown() throws Exception {
if (driver != null) {
driver.quit();
}
}
@Test
public void test_login_using_relative_locators_1(){
// Find the label element above the login text box
WebElement heightLabel = driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/h1"));
// Locate the textbox where username should be inputted
WebElement heightUserBox = driver.findElement(withTagName("input")
.below(heightLabel));
heightUserBox.sendKeys("user-name");
// Locate the textbox where password should be inputted
WebElement heightPasswordBox = driver.findElement(withTagName("input")
.below(heightUserBox));
heightPasswordBox.sendKeys("password");
// Locate the submit button
WebElement submitbutton = driver.findElement(By.xpath("//*[@id=\'app\']/section/form/div/div/button"));
submitbutton.click();
//Wait for 10 seconds to observe the output
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}

To find the input field where the username i.e. email-address has to be entered; we first locate the label that is above the input box using By.xpath method. To get the details of the web element i.e. XPath in this case, you should make use of Inspect option in the Chrome browser.

Code Walkthrough:

WebElement heightUserBox = driver.findElement(withTagName("input")

As seen in the above statement, the input argument to FindElement method is withTagName. On successful execution, it returns a RelativeLocator.RelativeBy object. The output will be relative to the WebElement heightLabel.

We use the located element to find the field where the username has to be inputted. As the input element (for the user name) is right below the label, we make use of the below option along with the withTagName() method.

WebElement heightLabel = driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/h1"));
// Locate the textbox where username should be inputted
WebElement heightUserBox = driver.findElement(withTagName("input")
.below(heightLabel));
heightUserBox.sendKeys("user-name");

The web element located below the email inputbox is the password inputbox. As the relative location of email inputbox is already known, the below option is used to locate the password inputbox.

WebElement heightPasswordBox = driver.findElement(withTagName("input")
.below(heightUserBox));
heightPasswordBox.sendKeys("password");

To execute the test, right-click on the project and select the option ‘Run As -> TestNG Test’.

Up Vote Down Vote 0 Votes
Posted 3 months ago
200 Views
1 Answer
3 months ago