Welcome to your first step into the world of test automation with Selenium WebDriver and Java! Whether you’re a beginner or looking to refresh your skills, in this course I will provide you clear explanations, practical code examples, and assignments to reinforce your learning.

Introduction to Selenium WebDriver

What is Selenium WebDriver?

Selenium WebDriver is a powerful tool for automating web application testing. It allows testers to programmatically control web browsers, mimicking user interactions to verify the functionality and behavior of web applications.

Components of Selenium

Selenium is not just a single tool but a suite comprising several components:

  • Selenium IDE: A record-and-playback tool for creating tests without coding.
  • Selenium WebDriver: A programming interface to create robust, browser-based automation tests.
  • Selenium Grid: A tool for running tests on different machines and browsers in parallel.

For this tutorial, we’ll focus on Selenium WebDriver.

WebDriver as a Java Interface

In Java, an interface defines a contract of methods that implementing classes must provide. Selenium WebDriver is designed as a Java interface, which means:

  • Blueprint: It outlines methods for browser automation without implementing them.
  • Implementation: Specific browser drivers (like ChromeDriver, FirefoxDriver) implement the WebDriver interface, providing concrete behavior for each method.

WebDriver as an API

An API (Application Programming Interface) allows different software components to communicate. Selenium WebDriver serves as an API between your Java code and the web browsers, enabling you to perform actions like clicking buttons, entering text, and verifying page titles.

Selenium WebDriver Architecture Diagram

Test Scripts

(Java, Python, C#, Ruby, JavaScript, etc.)

Selenium Client Libraries

(Language-specific bindings)

Protocols

(JSON Wire / W3C WebDriver)

Browser Drivers (WebDriver)

(ChromeDriver, GeckoDriver, etc.)

Web Browser

(Chrome, Firefox, Safari, Edge, etc.)






  • WebDriver Interface: The core interface with methods to control the browser.
  • RemoteWebDriver: Implements WebDriver and provides a base for browser-specific drivers.
  • Browser-Specific Drivers: Classes like ChromeDriver, FirefoxDriver, and EdgeDriver extend RemoteWebDriver to interact with their respective browsers.

Setting Up Your Development Environment

Before writing automation scripts, you need to set up your development environment.

Prerequisites

  • Java Development Kit (JDK): Ensure Java is installed on your machine.
  • Integrated Development Environment (IDE): Eclipse or IntelliJ IDEA are popular choices.
  • Web Browsers: Install browsers like Chrome, Firefox, and Edge for testing.
  • Maven: A build automation tool for managing project dependencies.

Approach 1: Manual Setup with JAR Files

Note: This approach is not recommended for beginners due to its manual nature and potential for errors.

Steps:

  1. Download Selenium WebDriver JARs:
    • Visit the official Selenium website.
    • Download the latest Selenium WebDriver Java JAR files (e.g., selenium-java-4.8.1.jar).
  2. Create a Java Project in Eclipse:
    • Open Eclipse and create a new Java project (e.g., SeleniumManualSetup).
  3. Attach JAR Files to the Project:
    • Right-click on the project > Properties > Java Build Path > Libraries > Add External JARs.
    • Select all downloaded JAR files and add them to the project.
  4. Handling Browser Drivers:Note: As of Selenium 4, browser-specific drivers are bundled, reducing the need for separate downloads.

Pros:

  • Direct control over JAR files.

Cons:

  • Time-consuming.
  • Prone to version mismatches.
  • Manual updates required for new Selenium versions.

Approach 2: Automated Setup with Maven

Recommended: Maven simplifies dependency management and automates updates.

Steps:

  1. Create a Maven Project in Eclipse:
    • Open Eclipse.
    • Navigate to File > New > Other > Maven Project.
    • Select Create a simple project and click Next.
    • Enter Group ID (e.g., com.example) and Artifact ID (e.g., SeleniumMavenSetup).
    • Click Finish.
  2. Configure pom.xml:
    • Open the pom.xml file in your Maven project.
    • Add Selenium WebDriver dependency:
    <dependencies>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>4.8.1</version> <!-- Use the latest version -->
            </dependency>
        </dependencies>
  3. Explanation:
    • groupId: The Selenium project’s group ID.
    • artifactId: The Selenium Java artifact.
    • version: Specify the desired Selenium version.
  4. Update Maven Project:
    • Right-click on the project > Maven > Update Project.
    • Ensure Force Update of Snapshots/Releases is checked.
    • Click OK to download and attach dependencies automatically.

Benefits of Maven:

  • Automated Dependency Management: Maven handles downloading and updating JAR files.
  • Consistency: Ensures all team members use the same library versions.
  • Scalability: Easily add more dependencies as your project grows.

Creating Your First Automation Test Case

With the environment set up, let’s create a simple automation script to validate the title of a web page.

Writing the Automation Script

Create a New Java Class:

  1. In your Maven project, navigate to src/test/java.
  2. Create a new package (e.g., com.example.tests).
  3. Within this package, create a new Java class (e.g., TitleVerificationTest).

Write the Test Code:

package com.example.tests;

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

public class TitleVerificationTest {
    public static void main(String[] args) {
        // Step 1: Launch Chrome Browser
        WebDriver driver = new ChromeDriver();

        // Step 2: Open the application URL
        driver.get("https://www.example.com");

        // Step 3: Validate the page title
        String actualTitle = driver.getTitle();
        String expectedTitle = "Example Domain";

        if (actualTitle.equals(expectedTitle)) {
            System.out.println("Test Passed: Title matches.");
        } else {
            System.out.println("Test Failed: Title does not match.");
        }

        // Step 4: Close the browser
        driver.close();
    }
}

Code Explanation: Line by Line

Package Declaration:

package com.example.tests;

Organizes the class within the com.example.tests package.

Import Statements:

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

Imports the WebDriver interface and ChromeDriver class from Selenium.

Class Declaration:

public class TitleVerificationTest {

Defines the TitleVerificationTest class.

Main Method:

public static void main(String[] args) {

The entry point of the Java application.

Step 1: Launch Chrome Browser:

WebDriver driver = new ChromeDriver();

Creates an instance of ChromeDriver, which launches the Chrome browser.

Step 2: Open the Application URL:

driver.get("https://www.example.com");

Navigates the browser to https://www.example.com.

Step 3: Validate the Page Title:

String actualTitle = driver.getTitle();
String expectedTitle = "Example Domain";

if (actualTitle.equals(expectedTitle)) {
    System.out.println("Test Passed: Title matches.");
} else {
    System.out.println("Test Failed: Title does not match.");
}

getTitle(): Retrieves the current page title.

Compares the actual title with the expected title.

Prints the test result to the console.

Step 4: Close the Browser:

driver.close();

Closes the browser window.

Running the Test Case

Execute the Test:

  • Right-click on TitleVerificationTest.java > Run As > Java Application.

Expected Outcome:

  • Chrome browser launches automatically.
  • Navigates to https://www.example.com.
  • Validates the page title.
  • Prints “Test Passed: Title matches.” in the console.
  • Closes the browser.

Examples and Assignments

Example: Launching Different Browsers

Modify the test case to run on different browsers like Edge and Firefox.

Launching Edge Browser:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;

public class TitleVerificationTestEdge {
    public static void main(String[] args) {
        // Step 1: Launch Edge Browser
        WebDriver driver = new EdgeDriver();

        // Step 2: Open the application URL
        driver.get("https://www.example.com");

        // Step 3: Validate the page title
        String actualTitle = driver.getTitle();
        String expectedTitle = "Example Domain";

        if (actualTitle.equals(expectedTitle)) {
            System.out.println("Test Passed: Title matches.");
        } else {
            System.out.println("Test Failed: Title does not match.");
        }

        // Step 4: Close the browser
        driver.close();
    }
}

Launching Firefox Browser:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TitleVerificationTestFirefox {
    public static void main(String[] args) {
        // Step 1: Launch Firefox Browser
        WebDriver driver = new FirefoxDriver();

        // Step 2: Open the application URL
        driver.get("https://www.example.com");

        // Step 3: Validate the page title
        String actualTitle = driver.getTitle();
        String expectedTitle = "Example Domain";

        if (actualTitle.equals(expectedTitle)) {
            System.out.println("Test Passed: Title matches.");
        } else {
            System.out.println("Test Failed: Title does not match.");
        }

        // Step 4: Close the browser
        driver.close();
    }
}

Key Points:

  • Driver Selection: Change the driver class (ChromeDriver, EdgeDriver, FirefoxDriver) based on the browser.
  • Browser Installation: Ensure the respective browser is installed on your system.
  • Dependency Management: Maven handles browser-specific drivers from Selenium 4 onwards.

Assignment: Automate Title Verification on a Different Website

Objective: Create an automation script to verify the title of a different website (e.g., https://www.wikipedia.org).

Steps:

  1. Create a New Java Class:
    • Package: com.example.tests
    • Class Name: WikipediaTitleTest
  2. Write the Test Code:
package com.example.tests;

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

public class WikipediaTitleTest {
    public static void main(String[] args) {
        // Step 1: Launch Chrome Browser
        WebDriver driver = new ChromeDriver();

        // Step 2: Open Wikipedia URL
        driver.get("https://www.wikipedia.org");

        // Step 3: Validate the page title
        String actualTitle = driver.getTitle();
        String expectedTitle = "Wikipedia";

        if (actualTitle.contains(expectedTitle)) {
            System.out.println("Test Passed: Title contains '" + expectedTitle + "'.");
        } else {
            System.out.println("Test Failed: Title does not contain '" + expectedTitle + "'.");
        }

        // Step 4: Close the browser
        driver.close();
    }
}

Explanation:

  • Validation Adjustment: Using contains to allow flexibility in title matching.
  • Expected Title: “Wikipedia” is a part of the actual title.

Run the Test:

  • Execute WikipediaTitleTest.java as a Java Application.
  • Verify the console output for test results.

Best Practices and Tips

  • Use Maven for Dependency Management: Simplifies adding, updating, and managing project dependencies.
  • Consistent Naming Conventions: Helps in maintaining readability and organization of your code.
  • Handle Exceptions Gracefully: Implement try-catch blocks to manage potential runtime exceptions.
  • Keep Tests Independent: Ensure each test case is independent to avoid cascading failures.
  • Regularly Update Selenium and Browser Drivers: Stay up-to-date to leverage new features and maintain compatibility.

Next Steps

In the upcoming tutorials, we will delve deeper into:

Locating Web Elements:

  • Understanding different locators: ID, Name, XPath, CSS Selectors, etc.
  • Best practices for selecting reliable locators.

Interacting with Web Elements:

  • Performing actions like clicking buttons, entering text, selecting from dropdowns.
  • Handling dynamic web elements and synchronization.

Advanced Testing Techniques:

  • Implementing TestNG for test management and reporting.
  • Parallel test execution.
  • Data-driven testing and parameterization.

Framework Development:

  • Building a robust automation framework.
  • Incorporating design patterns for scalability and maintainability.

Stay tuned, and happy automating!

Conclusion

Embarking on automated web testing with Selenium WebDriver and Java opens up a world of efficiency and reliability in ensuring your web applications perform as expected. By understanding the core concepts, setting up your environment correctly, and practicing with real-world examples, you’ll build a strong foundation for more advanced testing scenarios. Remember to follow best practices and continuously explore new features and updates in Selenium to keep your skills sharp and your testing robust.