DEV Community

Cover image for Practical Introduction to Web Application Testing with Selenium WebDriver and Java.
IKITAMA CODES
IKITAMA CODES

Posted on • Edited on

Practical Introduction to Web Application Testing with Selenium WebDriver and Java.

A Practical Introduction to Web Application Testing with Selenium WebDriver and Java.

Hello everyone,

Today, I want to share with you a practical introduction to testing web applications with Selenium WebDriver. We'll look at how to write a simple test script in Java, using two mini-projects I recently completed.

Setting Up the Environment

Before we start writing our test script, we need to prepare our development environment. Here’s what we need:

  1. Java JDK: Ensure that you have the Java Development Kit (JDK) installed.

  2. IntelliJ IDEA: We'll use IntelliJ IDEA as our IDE.

  3. Selenium WebDriver: We'll add the necessary libraries to the project.

  4. Google Chrome: We will use the Google Chrome browser.

  5. ChromeDriver: You’ll need to download the ChromeDriver that matches your version of Google Chrome.

Installing Selenium WebDriver

Step 1: Download Selenium WebDriver for Java.

  1. Go to the official Selenium WebDriver site by clicking this link https://www.selenium.dev/downloads/.

  2. Scroll down to the section Selenium Clients and WebDriver Language Bindings and download the Selenium WebDriver Java client. The download will be a ZIP file containing the libraries and the Selenium Java drivers.

  3. Visit https://sites.google.com/chromium.org/driver/downloads to find out which version of ChromeDriver to download based on your Google Chrome version.

    • How to check your Google Chrome version: In the URL bar of your Google Chrome browser, type: chrome://version.
  4. Create a new Java project with Maven in IntelliJ IDEA. In this case, we'll call it SeleniumTestLogiciels.

Step 2: Add Selenium Libraries to the Project.

  1. Extract the downloaded ZIP file to a folder on your computer.

  2. In IntelliJ IDEA, click on File > Project Structure.

  3. In the Project Structure window, click on Libraries.

  4. In the Libraries window, click the + icon on the right for (New Project Library) and then choose Java.

  5. In the Select Library Files window, navigate to the folder where you extracted Selenium WebDriver and select all the files inside it.

    • Quick selection tip: Click the first item in the folder, hold down the shift key, and then, without releasing the key, use the mouse to go to the bottom of the list and click on the last item. Voila! :).
  6. Click Apply and then Close.

Verify the Installation

Let’s create a simple test script to verify that Selenium WebDriver has been installed correctly.

  1. Create a new class named NewsletterSignUpTest.

  2. In the newly created class file, write a simple Selenium WebDriver test. Here’s an example script that opens one of my frontend projects in a web browser.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class NewsletterSignUpTest {

    public static void main(String[] args) throws InterruptedException {
        // Setup WebDriver
        System.setProperty("webdriver.chrome.driver","C:\\Selenium WebDriver Chrome\\chromedriver-win64\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        // Navigate to the page
        driver.get("https://time-tracking-dashboard-challenge-sooty.vercel.app/");

        // Maximize the browser window
        driver.manage().window().fullscreen();


        // Wait for 4 seconds before closing the browser
        Thread.sleep(6000);

        //close the browser
        driver.quit();
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Note: In the script above, replace C:\\Selenium WebDriver Chrome\\chromedriver-win64\\chromedriver.exe with the path to the ChromeDriver executable on your machine.
  1. Run the test script.
    • Note: If everything is set up correctly, this script should open a webpage in the Chrome browser and then close it.

Writing the Test Script for the NewsletterSignUp website

Below is the code for the NewsletterSignUpTest class we created earlier:


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.logging.Level;
import java.util.logging.Logger;

public class NewsletterSignUpTest {

    public static void main(String[] args){
        // Initialize logger for logging test results
        final Logger LOGGER = Logger.getLogger(NewsletterSignUpTest.class.getName());

        // Setup WebDriver
        System.setProperty("webdriver.chrome.driver","C:\\Selenium WebDriver Chrome\\chromedriver-win64\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

        try {
            // Navigate to the page
            driver.get("https://newsletter-sign-up-with-success-message-challenge-tau.vercel.app/");

            // Maximize the browser window
            driver.manage().window().fullscreen();

            // Wait for 5 seconds to observe the initial state
            Thread.sleep(5000);

            // Find the email input field and submit button
            WebElement emailInput = driver.findElement(By.id("email"));
            WebElement submitButton = driver.findElement(By.id("btnSubmit"));

            // Test invalid email submission
            emailInput.sendKeys("invalid-email");
            submitButton.click();

            // Wait for 4 seconds to observe the error message
            Thread.sleep(4000);

            // Verify the error message is displayed
            WebElement errorEmailMessage = driver.findElement(By.id("error-email"));
            String errorMessage = errorEmailMessage.getText();
            if ("Email is not in a valid format".equals(errorMessage)) {
                LOGGER.info("Invalid email test passed!");
            } else {
                LOGGER.severe("Invalid email test failed! Error message: " + errorMessage);
            }

            // Test valid email submission
            emailInput.clear();
            emailInput.sendKeys("validemail@example.com");
            submitButton.click();

            // Wait for 4 seconds to observe the success message
            Thread.sleep(4000);

            // Verify the success message is displayed
            WebElement successMessage = driver.findElement(By.id("card-success-message"));
            if (successMessage.isDisplayed()) {
                LOGGER.info("Valid email test passed!");
            } else {
                LOGGER.severe("Valid email test failed!");
            }


            // Verify the success email is correct
            WebElement successEmail = driver.findElement(By.id("user-email"));
            String displayedEmail = successEmail.getText();

            if ("validemail@example.com".equals(displayedEmail)) {
                LOGGER.info("Success email test passed!");
            } else {
                LOGGER.severe("Success email test failed! Displayed email: " + displayedEmail);
            }


            // Test dismissing the success message
            WebElement dismissButton = driver.findElement(By.id("btnDismissMessage"));
            dismissButton.click();

            // Wait for 4 seconds to observe the state after dismissing the success message
            Thread.sleep(4000);

            // Verify the sign-up form is displayed again
            WebElement signUpForm = driver.findElement(By.id("card-sign-up"));
            if (signUpForm.isDisplayed()) {
                LOGGER.info("Dismiss message test passed!");
            } else {
                LOGGER.severe("Dismiss message test failed!");
            }


            // Wait for 6 seconds before closing the browser
            Thread.sleep(6000);

        } catch (InterruptedException e) {
            // Log interrupted exception
            LOGGER.log(Level.SEVERE, "Interrupted exception occurred", e);
        }
        finally {
            // Close the browser
            driver.quit();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Note: In the script above, replace C:\\Selenium WebDriver Chrome\\chromedriver-win64\\chromedriver.exe with the path to the ChromeDriver executable on your machine.

Explanation of the Test Script for the NewsletterSignUp Website

To better understand how the Selenium WebDriver test script for the newsletter sign-up form works, we will examine each part of the code and explain its role.

WebDriver Initialization and Configuration

// Setup WebDriver
System.setProperty("webdriver.chrome.driver", "C:\\Selenium WebDriver Chrome\\chromedriver-win64\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Enter fullscreen mode Exit fullscreen mode

This part of the code initializes and configures the WebDriver to use ChromeDriver.

  • java System.setProperty sets the path to the ChromeDriver executable on your machine.

  • WebDriver driver = new ChromeDriver(); creates a new instance of ChromeDriver, which is used to interact with the Chrome browser.

Bloc Try-Catch

try {
    // Selenium test code
} catch (InterruptedException e) {
    // Handle interrupted exceptions
    LOGGER.log(Level.SEVERE, "Interrupted exception occurred", e);
} catch (Exception e) {
    // Handle other unexpected exceptions
    LOGGER.log(Level.SEVERE, "An unexpected exception occurred", e);
} finally {
    // Close the browser at the end of the test
    driver.quit();
}

Enter fullscreen mode Exit fullscreen mode
  • The try-catchblock surrounds the Selenium test code. It captures and handles exceptions that may occur during the test execution.

  • InterruptedException is specifically handled for interruptions during the use of Thread.sleep(), while Exception handles all other unexpected exceptions.

  • The finally block ensures that the browser is closed.

Navigation and Interaction with Page Elements

// Navigate to the form page
driver.get("https://newsletter-sign-up-with-success-message-challenge-tau.vercel.app/");

// Maximize the browser window
driver.manage().window().fullscreen();

Enter fullscreen mode Exit fullscreen mode
  • driver.get()Navigates to the specified URL where the newsletter sign-up form is located.

  • driver.manage().window().fullscreen()Maximizes the browser window for better visibility and interaction during testing

// Locate page elements
WebElement emailInput = driver.findElement(By.id("email"));
WebElement submitButton = driver.findElement(By.id("btnSubmit"));
Enter fullscreen mode Exit fullscreen mode
  • driver.findElement(By.id("email")) and driver.findElement(By.id("btnSubmit")) locate the page elements with the IDs email (email input field) et btnSubmit (form submission button).

Submitting Invalid Email

//Submit invalid email
emailInput.sendKeys("invalid-email");
submitButton.click();

Enter fullscreen mode Exit fullscreen mode
  • emailInput.sendKeys("invalid-email") enters an invalid email into the email field.

  • submitButton.click() clicks the Submit button to submit the form with the invalid email.

Verifying Messages

// Check for the error message display
WebElement errorEmailMessage = driver.findElement(By.id("error-email"));
String errorMessage = errorEmailMessage.getText();
if ("Email is not in a valid format".equals(errorMessage)) {
    LOGGER.info("Invalid email test passed!");
} else {
    LOGGER.severe("Invalid email test failed! Error message: " + errorMessage);
}

Enter fullscreen mode Exit fullscreen mode
  • driver.findElement(By.id("error-email")) locates the page element that displays the error message for an invalid email.

  • errorEmailMessage.getText() retrieves the text of the error message. The test checks if the expected error message is displayed and logs the result.

GitHub Project

For more practice, here’s the GitHub project that contains test scripts for the mini-projects written in JavaScript:.

  1. Newsletter sign-up form with success message.

  2. Time tracking dashboard.

Repository URL

Selinium_WebDriver_TestLogiciels_GitHub_Repository

Note: Please read the README.md file for details about this project.

Top comments (0)