End-to-End Automation Testing in Selenium

In this article, you will learn about how to write scripts for end-to-end automation testing of an application. We have learned in previous articles how to locate elements, how to interact with elements, and how to perform actions if a web driver failed to locate them in selenium. Now, we put all things in one place and try to write complete End to End testing for an application.

Pre-Requisites

  • Java Setup in your system
  • Maven installed – Read the Maven Article
  • Installed any IDE – We are using IntelliJ in this article.

Setup a new Maven Project in IntelliJ

You can see how to create a maven project in IntelliJ IDE from here.

Step 1  Navigate to File > New > Project.

Maven - Create a new Project
Fig 1 – Create a new Project

Step 2  Now In the New Project section, fill the details – Name, Preferred Location, Language as Java, Build System as Maven, and select JDK.

Fill Project Details
Fig 2 – Fill Project Details

Under advanced Settings, you can write GroupId and ArtifactId. And then click Create.

Step 3  After finishing, you can see the project structure in your IDE which is shown in the below screenshot.

Maven Project Structure
Fig 3 – Maven Project Structure

Step 4  Now open the pom.xml file and you can add the given dependencies under the <dependencies></dependencies> tag.

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

After adding this dependency, your pom.xml file looks like this –

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
    <artifactId>selenium-e2e-testing</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

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

</project>

Step 5  After that, reload the maven project. And all the dependencies will be downloaded inside the External Libraries folder.

Creating Test Package and Test Class

Step 1 Create a new Package under src/test/java folder – seleniumTest

Create package
Fig 4 – Create package

Step 2 – Create a new Test class under src/test/java/seleniumTest package – EndToEndTest

Create java class
Fig 5 – Create java class

Step 3 – Create a resources folder inside the src/test folder. And put the chrome driver in that src/test/resources folder.

Create resources directory
Fig 6 – Create resources directory

Download your browser-compatible chrome driver from here

Move the chromedriver inside resources
Fig 7 – Move the chromedriver inside resources

Step 4 – Create the main class in EndToEndTest class. And write the complete code to test a scenario.

Complete E2E Selenium Test

Test Scenario – Login into the application and complete checkout of a product.

Demo Test Website – https://www.saucedemo.com/

Note - We have used Thread.sleep method only for making execution slow.
package seleniumTest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

public class EndToEndTest {

    public static void main(String[] args) throws InterruptedException {
        // Create the WebDriver instance
        System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        // Navigate to website
        driver.get("https://www.saucedemo.com/");

        // Login to the application
        WebElement input_username = driver.findElement(By.id("user-name"));
        input_username.sendKeys("standard_user");
        WebElement input_password = driver.findElement(By.id("password"));
        input_password.sendKeys("secret_sauce");
        WebElement button_login = driver.findElement(By.id("login-button"));
        // adding sleep method for slow execution.
        Thread.sleep(1000);
        button_login.click();

        // select a product - Product Name = Sauce Labs Onesie
        String productName = "Sauce Labs Onesie";
        List<WebElement> allProductsName = driver.findElements(By.className("inventory_item_name"));
        for (WebElement product : allProductsName) {
            if (product.getText().equals(productName)) {
                Thread.sleep(1000);
                product.click();
                break;
            }
        }

        // navigate to product detail page and verify the correct selected product
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("back-to-products"))));

        WebElement label_productTitle = driver.findElement(By.className("inventory_details_name"));
        String productTitle = label_productTitle.getText();

        if (productTitle.equals(productName)) {
            System.out.println("Product Details: Product matched.");
        } else {
            System.out.println("Product Details: Wrong item.");
        }

        // click add to cart button
        WebElement button_addToCart = driver.findElement(By.cssSelector("button[id^='add-to-cart']"));
        Thread.sleep(1000);
        button_addToCart.click();

        // go to cart page
        WebElement button_goToCart = driver.findElement(By.className("shopping_cart_link"));
        Thread.sleep(1000);
        button_goToCart.click();

        // click checkout button
        WebElement button_checkout = driver.findElement(By.id("checkout"));
        Thread.sleep(1000);
        button_checkout.click();
        
        // enter details and click continue
        String firstName = "Shubham";
        String lastName = "Kumar";
        String zipCode = "123455";

        WebElement input_firstName = driver.findElement(By.id("first-name"));
        input_firstName.sendKeys(firstName);

        WebElement input_lastName = driver.findElement(By.id("last-name"));
        input_lastName.sendKeys(lastName);

        WebElement input_zipCode = driver.findElement(By.id("postal-code"));
        input_zipCode.sendKeys(zipCode);

        WebElement button_continue = driver.findElement(By.id("continue"));
        Thread.sleep(1000);
        button_continue.click();
        
        // verify product on checkout page and click finish
        WebElement label_productTitleOnCheckout = driver.findElement(By.className("inventory_item_name"));
        productTitle = label_productTitleOnCheckout.getText();

        if (productTitle.equals(productName)) {
            System.out.println("Checkout: Product matched.");
        } else {
            System.out.println("Checkout: Wrong item.");
        }

        WebElement button_finish = driver.findElement(By.id("finish"));
        Thread.sleep(1000);
        button_finish.click();
        
        // verify
        String expectMessage = "THANK YOU FOR YOUR ORDER";
        WebElement label_completeMessage = driver.findElement(By.className("complete-header"));
        String actualMessage = label_completeMessage.getText();

        if (expectMessage.equals(actualMessage)) {
            System.out.println("Success: Item checkout.");
        } else {
            System.out.println("Fail: Item checkout.");
        }

        Thread.sleep(1000);

        // close the WebDriver instance
        driver.close();
    }

}

We can divide the same code into small separate methods on the basis of their functionality.

1. Create a method for launching the application –

    public static void launchApplication() {
        try {
            System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
            driver = new ChromeDriver();
            driver.manage().window().maximize();
            driver.get("https://www.saucedemo.com/");
        } catch (Exception e) {
            throw new RuntimeException("Failed to launch application.");
        }
    }

2. Create a method for login into the application –

    public static void login() {
        try {
            WebElement input_username = driver.findElement(By.id("user-name"));
            input_username.sendKeys("standard_user");
            WebElement input_password = driver.findElement(By.id("password"));
            input_password.sendKeys("secret_sauce");
            WebElement button_login = driver.findElement(By.id("login-button"));
            // adding sleep method for slow execution.
            Thread.sleep(1000);
            button_login.click();
        } catch (Exception e) {
            throw new RuntimeException("Failed to login.");
        }
    }

You can create all the methods like this, and call those methods. You can see the complete code below. There are 2 classes one is for calling all methods and one is for writing all the functionalities.

package seleniumTestUsingMethods;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

public class Functionality {

    public static WebDriver driver;
    public static String productTitle;

    public void launchApplication(String url) {
        try {
            System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
            driver = new ChromeDriver();
            driver.manage().window().maximize();
            driver.get(url);
        } catch (Exception e) {
            throw new RuntimeException("Failed to launch application.");
        }
    }

    public void login(String username, String password) {
        try {
            WebElement input_username = driver.findElement(By.id("user-name"));
            input_username.sendKeys(username);
            WebElement input_password = driver.findElement(By.id("password"));
            input_password.sendKeys(password);
            WebElement button_login = driver.findElement(By.id("login-button"));
            Thread.sleep(1000);
            button_login.click();
        } catch (Exception e) {
            throw new RuntimeException("Failed to login.");
        }
    }

    public void selectProduct(String productName) {
        try {
            List<WebElement> allProductsName = driver.findElements(By.className("inventory_item_name"));
            for (WebElement product : allProductsName) {
                if (product.getText().equals(productName)) {
                    Thread.sleep(1000);
                    product.click();
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to select product.");
        }
    }

    public void verifyProductDetailsPage(String productName) {
        try {
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("back-to-products"))));

            WebElement label_productTitle = driver.findElement(By.className("inventory_details_name"));
            productTitle = label_productTitle.getText();

            if (productTitle.equals(productName)) {
                System.out.println("Product Details: Product matched.");
            } else {
                System.out.println("Product Details: Wrong item.");
            }
        } catch (Exception e) {
            throw new RuntimeException("Fail to verify product details on product details page.");
        }
    }

    public void addProductInCart() {
        try {
            WebElement button_addToCart = driver.findElement(By.cssSelector("button[id^='add-to-cart']"));
            Thread.sleep(1000);
            button_addToCart.click();
        } catch (Exception e) {
            throw new RuntimeException("Fail to add product in cart.");
        }
    }

    public void goToCartPage() {
        try {
            WebElement button_goToCart = driver.findElement(By.className("shopping_cart_link"));
            Thread.sleep(1000);
            button_goToCart.click();
        } catch (Exception e) {
            throw new RuntimeException("Fail to navigate to cart page.");
        }
    }

    public void goToCheckoutPage() {
        try {
            WebElement button_checkout = driver.findElement(By.id("checkout"));
            Thread.sleep(1000);
            button_checkout.click();
        } catch (Exception e) {
            throw new RuntimeException("Fail to navigate to checkout page.");
        }
    }

    public void enterPersonalDetails(String firstName, String lastName, String zipCode) {
        try {
            WebElement input_firstName = driver.findElement(By.id("first-name"));
            input_firstName.sendKeys(firstName);

            WebElement input_lastName = driver.findElement(By.id("last-name"));
            input_lastName.sendKeys(lastName);

            WebElement input_zipCode = driver.findElement(By.id("postal-code"));
            input_zipCode.sendKeys(zipCode);

            WebElement button_continue = driver.findElement(By.id("continue"));
            Thread.sleep(1000);
            button_continue.click();
        } catch (Exception e) {
            throw new RuntimeException("Fail to enter personal details.");
        }
    }

    public void verifyProductCheckoutPageAndCompleteCheckout(String productName) {
        try {
            WebElement label_productTitleOnCheckout = driver.findElement(By.className("inventory_item_name"));
            productTitle = label_productTitleOnCheckout.getText();

            if (productTitle.equals(productName)) {
                System.out.println("Checkout: Product matched.");
            } else {
                System.out.println("Checkout: Wrong item.");
            }
            WebElement button_finish = driver.findElement(By.id("finish"));
            Thread.sleep(1000);
            button_finish.click();
        } catch (Exception e) {
            throw new RuntimeException("Fail to verify product details on checkout page.");
        }
    }

    public void verifySuccessMessage() {
        try {
            String expectMessage = "THANK YOU FOR YOUR ORDER";
            WebElement label_completeMessage = driver.findElement(By.className("complete-header"));
            String actualMessage = label_completeMessage.getText();

            if (expectMessage.equals(actualMessage)) {
                System.out.println("Success: Item checkout.");
            } else {
                System.out.println("Fail: Item checkout.");
            }

            Thread.sleep(1000);
        } catch (Exception e) {
            throw new RuntimeException("Fail to verify success message.");
        }
    }

    public void closeBrowser() {
        try {
            driver.quit();
        } catch (Exception e) {
            throw new RuntimeException("Fail to close browser.");
        }
    }

}

package seleniumTestUsingMethods;

public class EndToEndTest {

    public static void main(String[] args) {

        Functionality functionality = new Functionality();

        functionality.launchApplication("https://www.saucedemo.com/");
        functionality.login("standard_user", "secret_sauce");
        functionality.selectProduct("Sauce Labs Onesie");
        functionality.verifyProductDetailsPage("Sauce Labs Onesie");
        functionality.addProductInCart();
        functionality.goToCartPage();
        functionality.goToCheckoutPage();
        functionality.enterPersonalDetails("Shubham", "Kumar", "123455");
        functionality.verifyProductCheckoutPageAndCompleteCheckout("Sauce Labs Onesie");
        functionality.verifySuccessMessage();
        functionality.closeBrowser();

    }
}

Running the Test

To run the test case do right-click on your Java file and click on run. It will start executing –

Fig 8 – Run the test case

Conclusion

Now you can create automation scripts for any application and can test. But It does not end here. There are a lot of things that need to add. This framework is very simple just creating the main class and putting all the methods in the same. It is not a good practice, In the upcoming articles, you will see how to integrate BDD – Behaviour Driven Development, JUnit, or TestNG with our testing framework that makes it more readable and reliable.

Resources

You might Like

💖 If you like this article please make sure to Like, Comment, and Share it with your friends and colleagues.

Follow us on our social networks –