Enhancing Test Automation Frameworks with Helper Utilities for WebElement Interaction

Enhancing Test Automation Frameworks with Helper Utilities for WebElement Interaction

Creating a robust test automation framework is key to ensuring that your tests are maintainable, scalable, and efficient. One of the best practices in developing such a framework is to create Helper Utilities. These utilities abstract common actions and interactions with the web elements, allowing your test scripts to be more readable and reusable. In this blog post, we will discuss how to create Helper Generic Utilities and demonstrate their usage in your test scripts using Selenium WebDriver.

Why Use Helper Utilities?

Helper Generic Utilities are reusable methods that perform common actions like clicking elements, entering text, selecting from dropdowns, and waiting for elements to be visible or clickable. By encapsulating these actions in utility methods, you achieve the following benefits:

- Readability: Test scripts become cleaner and easier to read.

- Reusability: Common actions can be reused across multiple test scripts.

- Maintainability: Changes in the UI can be managed in a single place, reducing the need to update multiple test scripts.

<dependencies>     
  
     <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.18.1</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.9.0</version>
            <scope>test</scope>
        </dependency>
      
        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>1.0.2</version>
        </dependency>

</dependencies>        

Adding Dependencies to your Maven Project - Pom.xml File

Let's start by adding important dependencies in your Maven project


Step 1: Use the Utility Class in Your Test Scripts


Creating Helper Generic Utilities for WebElement Interaction

Step 2: Create the Utility Class

Creating a class WebLocatorActions that contains various helper methods to interact with web elements. We will then use this utility class in our test scripts.

Here is an example of a utility class named WebLocatorActions that provides methods for common web interactions:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.Select;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.openqa.selenium.interactions.Actions;

import java.time.Duration;

public class WebLocatorActions {

    private WebDriver driver;

    private static long explicitTimeout = 15;

    // Constructor to initialize WebDriver

    public WebLocatorActions(WebDriver driver) {

        this.driver = driver;

    }

    public WebElement findElement(String locatorType, String locatorValue) {

        return switch (locatorType.toLowerCase()) {

            case "id" -> driver.findElement(By.id(locatorValue));

            case "name" -> driver.findElement(By.name(locatorValue));

            case "classname" -> driver.findElement(By.className(locatorValue));

            case "tagname" -> driver.findElement(By.tagName(locatorValue));

            case "linktext" -> driver.findElement(By.linkText(locatorValue));

            case "partiallink" -> driver.findElement(By.partialLinkText(locatorValue));

            case "css" -> driver.findElement(By.cssSelector(locatorValue));

            case "xpath" -> driver.findElement(By.xpath(locatorValue));

            default -> throw new IllegalArgumentException("Unknown locator type: " + locatorType);

        };

    }

    public void enterText(String locatorType, String locatorValue, String value) {

        WebElement ele = findElement(locatorType, locatorValue);

        if (ele.isEnabled()) {

            ele.clear();

            ele.sendKeys(value);

        }

    }

    public void clickElement(String locatorType, String locatorValue) {

        WebElement ele = findElement(locatorType, locatorValue);

        if (ele.isEnabled() & ele.isDisplayed()) {

            ele.click();

        }

    }

    public void checkElement(String locatorType, String locatorValue) {

        WebElement ele = findElement(locatorType, locatorValue);

        if (ele.isEnabled() && ele.isDisplayed() && !ele.isSelected()) {

            ele.click();

        }

    }

    public void selectFromDropDownByValue(String locatorType, String locatorValue, String value) {

        WebElement ele = findElement(locatorType, locatorValue);

        Select select = new Select(ele);

        if (ele.isEnabled()) {

            select.selectByValue(value);

        }

    }

    public void selectFromDropDownByIndex(String locatorType, String locatorValue, int index) {

        WebElement ele = findElement(locatorType, locatorValue);

        Select select = new Select(ele);

        if (ele.isEnabled()) {

            select.selectByIndex(index);

        }

    }

    public void moveToElement(String locatorType, String locatorValue) {

        WebElement ele = findElement(locatorType, locatorValue);

        Actions action = new Actions(driver);

        action.moveToElement(ele).pause(200).perform();

    }

    public boolean elementIsEnabled(String locatorType, String locatorValue) {

        WebElement ele = findElement(locatorType, locatorValue);

        return ele.isEnabled();

    }

    public boolean elementIsDisplayed(String locatorType, String locatorValue) {

        WebElement ele = findElement(locatorType, locatorValue);

        return ele.isDisplayed();

    }

    public void waitForElementToBeClickable(String locatorType, String locatorValue) {

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(explicitTimeout));

        wait.until(ExpectedConditions.elementToBeClickable(findElement(locatorType, locatorValue)));

    }

    public void waitForElementToBeVisible(String locatorType, String locatorValue) {

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(explicitTimeout));

        wait.until(ExpectedConditions.visibilityOf(findElement(locatorType, locatorValue)));

    }

}        

Step 3: Use the Utility Class in Your Test Scripts

Now that we have our utility class, let's use it in our test scripts to perform various actions. Below is an example of how to use WebLocatorActions in test scripts to create an account and log in to an e-commerce site.

import com.github.javafaker.Faker;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.testng.annotations.AfterSuite;

import org.testng.annotations.BeforeSuite;

import org.testng.annotations.Test;

import java.time.Duration;

public class ECommerceTesting {

    public static WebDriver driver;

    public static Faker fk = new Faker();

    public static String email;

    public static String password;

    Asmita Shukla 

    public void setup() {

        ChromeOptions options = new ChromeOptions();

        options.addArguments("--start-maximized");

        options.addArguments("--disable-notifications");

        options.addArguments("--blink-settings=imagesEnabled=false");

        driver = new ChromeDriver(options);

        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

        driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(35));

        driver.get("https://magento.softwaretestingboard.com/");

        

        email = fk.internet().safeEmailAddress();

        password = "Test@1999";

    }

    @AfterSuite

    public void tearDown() {

        driver.quit();

    }

    @Test(priority = 1)

    public void CreateAccountTest() {

        WebLocatorActions webLocatorActions = new WebLocatorActions(driver);

        webLocatorActions.waitForElementToBeClickable("xpath", "(//a[normalize-space()='Create an Account'])[1]");

        webLocatorActions.clickElement("xpath", "(//a[normalize-space()='Create an Account'])[1]");

        webLocatorActions.waitForElementToBeVisible("xpath", "https://input[@id='firstname']");

        webLocatorActions.enterText("xpath", "https://input[@id='firstname']", fk.name().firstName());

        webLocatorActions.enterText("xpath", "https://input[@id='lastname']", fk.name().lastName());

        webLocatorActions.enterText("xpath", "https://input[@id='email_address']", email);

        webLocatorActions.enterText("xpath", "https://input[@id='password']", password);

        webLocatorActions.enterText("xpath", "https://input[@id='password-confirmation']", password);

        webLocatorActions.clickElement("xpath", "https://button[@title='Create an Account']//span[contains(text(),'Create an Account')]");

        webLocatorActions.waitForElementToBeVisible("xpath", "(//div[@role='alert']//div[contains(normalize-space(),'Thank you for registering with Main Website Store')])[1]");

    }

    @Test(priority = 2, dependsOnMethods = "CreateAccountTest")

    public void LoginInTest() {

        driver.manage().deleteAllCookies();

        driver.get("https://magento.softwaretestingboard.com/");

        WebLocatorActions webLocatorActions = new WebLocatorActions(driver);

        webLocatorActions.waitForElementToBeClickable("xpath", "(//a[contains(text(),'Sign In')])[1]");

        webLocatorActions.clickElement("xpath", "(//a[contains(text(),'Sign In')])[1]");

        webLocatorActions.waitForElementToBeVisible("xpath", "https://fieldset[@class='fieldset login']//span[contains(text(),'Sign In')]");

        webLocatorActions.enterText("id", "email", email);

        webLocatorActions.enterText("xpath", "https://fieldset[@class='fieldset login']//input[@id='pass']", password);

        webLocatorActions.clickElement("xpath", "https://fieldset[@class='fieldset login']//span[contains(text(),'Sign In')]");

        webLocatorActions.waitForElementToBeVisible("xpath", "(//span[contains(normalize-space(),'Welcome')])[1]");

    }

}        

Conclusion

By creating Helper Generic Utilities, you can significantly enhance the readability, reusability, and maintainability of your test scripts. The WebLocatorActions class shown in this post is an example of how to encapsulate common web actions into reusable methods. Integrating these utilities into your test framework allows you to write cleaner and more efficient test scripts, ultimately leading to more reliable test automation.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了