Monday, 31 October 2016

Selenium Automation Real-Time Project with Java: Step-by-Step Implementation Guide.

 

Selenium Automation Real-Time Project with Java: Step-by-Step Implementation Guide

SEO Title: Selenium Automation Real-Time Project with Java – Complete Tutorial

Meta Description: Learn Selenium automation with Java through a practical e-commerce testing project. Explore Maven, TestNG, Page Object Model, test data, assertions and framework development.

Suggested URL Slug: /blog/selenium-automation-real-time-project-java/

Primary Keyword: Selenium Automation Real-Time Project with Java

Secondary Keywords: Selenium Java project, Selenium automation framework project, Selenium WebDriver real-time project, Selenium TestNG project, Selenium Maven framework, Selenium practical training Kolkata.


Introduction

Learning Selenium WebDriver and Java programming is an important first step towards becoming an Automation Test Engineer. However, understanding individual commands is not enough to demonstrate practical automation skills during technical interviews or professional projects.

Employers often expect candidates to understand how to automate a complete business workflow, organise test scripts, manage test data, develop reusable components and generate meaningful execution reports.

A practical Selenium project helps bridge the gap between theoretical learning and real-world automation testing.

In this tutorial, we will develop a sample e-commerce application automation project using Selenium WebDriver with Java. The project will demonstrate browser automation, login validation, product selection, shopping cart verification, Maven dependency management, TestNG execution and Page Object Model implementation.

The example uses a demonstration application. The locators and workflows should be adapted to the actual application selected for your project.

1. Project Objective: Automate an E-Commerce Application

Consider an online shopping application with the following features:

  • User login.

  • Product listing.

  • Product selection.

  • Shopping cart.

  • Checkout.

  • Order confirmation.

  • Logout.

The objective is to automate important user journeys and verify whether the application behaves as expected.

Project test scenarios

Test Case IDTest ScenarioExpected Result
TC001Valid loginUser reaches the product page
TC002Invalid loginAppropriate error message appears
TC003View product listProducts are displayed
TC004Add product to cartProduct is added successfully
TC005Verify cartSelected product appears
TC006Remove productProduct is removed from cart
TC007CheckoutCheckout page opens
TC008Complete orderOrder confirmation appears
TC009LogoutUser session ends

These test cases provide a starting point for building a functional automation suite.

2. Tools and Technologies Required

The following technologies can be used:

ToolPurpose
JavaProgramming language
Selenium WebDriverBrowser automation
Eclipse or IntelliJ IDEADevelopment environment
MavenDependency management
TestNGTest execution
Page Object ModelFramework architecture
Git and GitHubVersion control
JenkinsContinuous integration
Selenium GridParallel browser execution

You should have a basic understanding of Java classes, objects, methods, inheritance and exception handling before developing the project.

3. Create the Selenium Maven Project

Create a new Maven project in Eclipse or IntelliJ IDEA.

Use the following project details:

  • Group ID: com.palium.ecommerce

  • Artifact ID: ecommerce-automation

  • Version: 1.0-SNAPSHOT

Create the following project structure:

ecommerce-automation
│
├── pom.xml
│
└── src
    ├── main
    │   └── java
    │       ├── base
    │       ├── pages
    │       └── utilities
    │
    └── test
        ├── java
        │   └── tests
        │
        └── resources
            ├── config.properties
            └── testng.xml

The pages package contains Page Object classes, base contains browser management, utilities contains reusable methods and tests contains the actual test cases.

4. Configure Selenium and TestNG Dependencies

Open pom.xml and add the Selenium and TestNG dependencies.

The following example uses Selenium 4.38.0 and TestNG 7.11.0. These are illustrative dependency versions; check current stable releases and compatibility before starting a new project.

<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
         https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.palium.ecommerce</groupId>
    <artifactId>ecommerce-automation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.release>17</maven.compiler.release>
        <selenium.version>4.38.0</selenium.version>
        <testng.version>7.11.0</testng.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
                <configuration>
                    <release>17</release>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.5.4</version>
            </plugin>

        </plugins>
    </build>

</project>

Save the file and update the Maven project so that the dependencies are downloaded.

5. Create Browser Management Using BaseTest

The BaseTest class manages browser setup and cleanup.

Create BaseTest.java under src/test/java/base.

package base;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;

public class BaseTest {

    protected WebDriver driver;

    @BeforeMethod
    public void setUp() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

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

    @AfterMethod(alwaysRun = true)
    public void tearDown() {

        if (driver != null) {
            driver.quit();
        }
    }
}

This example uses the public SauceDemo demonstration application as the practice environment.

Selenium Manager can automatically manage compatible browser drivers in many standard setups, reducing manual driver configuration.

6. Develop the Login Page Using Page Object Model

The Login Page class contains the locators and actions required to perform login operations.

Create LoginPage.java under the pages package.

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage {

    WebDriver driver;

    By username =
        By.id("user-name");

    By password =
        By.id("password");

    By loginButton =
        By.id("login-button");

    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }

    public void enterUsername(String user) {
        driver.findElement(username).sendKeys(user);
    }

    public void enterPassword(String pass) {
        driver.findElement(password).sendKeys(pass);
    }

    public void clickLogin() {
        driver.findElement(loginButton).click();
    }

    public void login(
            String user,
            String pass) {

        enterUsername(user);
        enterPassword(pass);
        clickLogin();
    }
}

The Page Object Model approach keeps page-specific interactions separate from the test cases.

7. Create the Product Page Class

After successful login, the user reaches the product listing page.

Create ProductPage.java.

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class ProductPage {

    WebDriver driver;

    By firstProduct =
        By.id("add-to-cart-sauce-labs-backpack");

    By cartIcon =
        By.className("shopping_cart_link");

    public ProductPage(WebDriver driver) {
        this.driver = driver;
    }

    public void addFirstProduct() {
        driver.findElement(firstProduct).click();
    }

    public void openCart() {
        driver.findElement(cartIcon).click();
    }
}

This class provides reusable methods for adding a product to the cart and opening the shopping cart.

8. Create the First Login Automation Test

Create LoginTest.java under the tests package.

package tests;

import base.BaseTest;
import pages.LoginPage;

import org.testng.Assert;
import org.testng.annotations.Test;

public class LoginTest extends BaseTest {

    @Test
    public void validLoginTest() {

        LoginPage loginPage =
            new LoginPage(driver);

        loginPage.login(
            "standard_user",
            "secret_sauce"
        );

        Assert.assertTrue(
            driver.getCurrentUrl()
                .contains("inventory"),
            "Login failed"
        );
    }
}

This test:

  1. Launches Chrome.

  2. Opens the demonstration application.

  3. Enters valid credentials.

  4. Clicks the login button.

  5. Verifies that the product listing page is displayed.

Use the application's published demonstration credentials and verify that they remain valid before running the test.

9. Automate the Add-to-Cart Scenario

Now create a test for adding a product to the shopping cart.

package tests;

import base.BaseTest;
import pages.LoginPage;
import pages.ProductPage;

import org.testng.Assert;
import org.testng.annotations.Test;

public class AddToCartTest extends BaseTest {

    @Test
    public void addProductToCartTest() {

        LoginPage loginPage =
            new LoginPage(driver);

        ProductPage productPage =
            new ProductPage(driver);

        loginPage.login(
            "standard_user",
            "secret_sauce"
        );

        productPage.addFirstProduct();

        productPage.openCart();

        Assert.assertTrue(
            driver.getPageSource().contains(
                "Sauce Labs Backpack"
            ),
            "Product not found in cart"
        );
    }
}

The test verifies that the selected product appears in the cart.

For a production-quality test, use a dedicated cart page object and an explicit wait to verify the product's presence rather than relying on a broad page-source search.

10. Automate Negative Login Testing

Negative testing verifies how an application behaves when invalid information is entered.

Create a test using an invalid password.

package tests;

import base.BaseTest;
import pages.LoginPage;

import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;

public class InvalidLoginTest extends BaseTest {

    @Test
    public void invalidLoginTest() {

        LoginPage loginPage =
            new LoginPage(driver);

        loginPage.login(
            "standard_user",
            "wrong_password"
        );

        String errorMessage =
            driver.findElement(
                By.cssSelector("[data-test='error']")
            ).getText();

        Assert.assertTrue(
            errorMessage.contains(
                "Username and password do not match"
            ),
            "Expected login error was not displayed"
        );
    }
}

This test verifies that the application displays an appropriate error message for invalid credentials.

11. Introduce Explicit Waits

Real-world applications may load elements dynamically. Hardcoded delays can make test execution unnecessarily slow and unreliable.

Use explicit waits to synchronise test execution.

Example:

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

WebElement loginButton = wait.until(
    ExpectedConditions.elementToBeClickable(
        By.id("login-button")
    )
);

loginButton.click();

A robust framework should centralise common waiting methods in a reusable utility class.

12. Add Test Data Using TestNG DataProvider

Instead of writing separate test methods for every login combination, use a TestNG DataProvider.

@DataProvider(name = "loginData")
public Object[][] getLoginData() {

    return new Object[][] {

        {"standard_user", "secret_sauce"},

        {"invalid_user", "wrong_password"}

    };
}

The test method can receive these values as parameters.

@Test(dataProvider = "loginData")
public void loginTest(
        String username,
        String password) {

    LoginPage loginPage =
        new LoginPage(driver);

    loginPage.login(username, password);

}

For a complete implementation, separate positive and negative expected results so that each data set has an appropriate assertion.

13. Execute Tests Using TestNG XML

Create a testng.xml file under src/test/resources.

<!DOCTYPE suite SYSTEM
    "https://testng.org/testng-1.0.dtd">

<suite name="Ecommerce Automation Suite">

    <test name="Ecommerce Tests">

        <classes>

            <class name="tests.LoginTest"/>

            <class name="tests.AddToCartTest"/>

            <class name="tests.InvalidLoginTest"/>

        </classes>

    </test>

</suite>

Configure Maven Surefire Plugin to execute the suite XML file if you want Maven to run this specific suite.

You can then execute:

mvn clean test

Maven will compile the project and execute the configured tests.

14. Add Reporting and Screenshot Capture

A professional automation project should generate reports that help developers and testers understand execution results.

Reports should ideally include:

  • Test case name.

  • Execution status.

  • Execution time.

  • Failure reason.

  • Error details.

  • Screenshots where relevant.

TestNG provides basic execution reports. Additional reporting tools such as ExtentReports can be integrated when richer dashboards are required.

Screenshot capture can be implemented through Selenium's TakesScreenshot interface and triggered from a TestNG listener when a test fails.

15. Integrate the Project with GitHub and Jenkins

Once the automation framework is working locally, store the project in GitHub.

A typical workflow is:

  1. Create a Git repository.

  2. Commit the Selenium Maven project.

  3. Push the code to GitHub.

  4. Configure a Jenkins job or pipeline.

  5. Connect Jenkins to the repository.

  6. Configure Java and Maven.

  7. Execute mvn clean test.

  8. Publish the execution results.

This approach helps teams run automation tests regularly and detect regressions during software development.

16. Challenges You May Face During a Real-Time Project

1. Dynamic elements

Use stable locators and appropriate explicit waits. Avoid relying on changing element indexes.

2. Test data conflicts

Ensure that test cases use independent accounts or records, particularly when tests run in parallel.

3. Browser compatibility

Validate the application on supported browser versions and use Selenium Grid when multiple environments are required.

4. Unstable test execution

Investigate timing problems, shared state, network issues and application defects instead of relying on repeated retries.

5. Difficult failure diagnosis

Capture screenshots, logs, browser information and meaningful error messages.

6. Framework maintenance

Use Page Object Model, reusable utilities and consistent naming conventions to reduce duplication.

17. What Should You Include in Your Selenium Project Portfolio?

A good project portfolio can demonstrate your practical automation skills during interviews.

Include:

  • Project objective and application description.

  • Test scenario documentation.

  • Selenium framework architecture.

  • Java source code.

  • Maven configuration.

  • TestNG suite configuration.

  • Page Object Model implementation.

  • Test data management.

  • Execution reports.

  • Screenshots of important test results.

  • GitHub repository, if the code can be shared.

  • Challenges faced and solutions implemented.

Do not publish passwords, personal information or confidential application data in a public repository.

Learn Real-Time Selenium Automation at Palium Skills

Palium Skills offers practical Automation Testing training designed to help freshers, manual testers and working professionals develop real-world automation skills.

The Selenium with Java training path can cover:

  • Java programming for automation.

  • Selenium WebDriver.

  • XPath and CSS selectors.

  • Browser handling and synchronisation.

  • Maven and TestNG.

  • Page Object Model.

  • Data-driven testing.

  • Selenium Grid and parallel execution.

  • Automation framework development.

  • Reporting and logging.

  • Git, Jenkins and CI/CD fundamentals.

  • End-to-end automation project implementation.

Training options include classroom sessions at South Kolkata and Salt Lake centres, as well as instructor-led live online sessions for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar, Near South City Mall, Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Enquire about Selenium with Java, Selenium with Python and Playwright Automation Testing training at Palium Skills.

Frequently Asked Questions (FAQs)

1. What is a real-time Selenium project?

A real-time Selenium project involves automating actual business workflows, such as login, product selection, checkout, form submission or employee management, using Selenium WebDriver.

2. Which application can beginners use for Selenium practice?

Beginners can use publicly available demonstration applications such as SauceDemo to practise login, product selection, cart management and checkout workflows.

3. Which framework is best for Selenium Java projects?

A combination of Selenium WebDriver, Java, Maven, TestNG and Page Object Model provides a practical foundation for many Java-based automation projects.

4. How many test cases should a Selenium project contain?

The number depends on the application's functionality and project objectives. A learning project can begin with 10–20 meaningful scenarios and expand as the framework develops.

5. Is Maven necessary for a Selenium project?

No, but Maven is useful for dependency management, project organisation and automated test execution.

6. How do I make my Selenium project suitable for interviews?

Include a working framework, meaningful test cases, reusable page classes, test data, reports and a clear explanation of the challenges you solved.

7. Can Selenium projects be integrated with Jenkins?

Yes. Jenkins can retrieve the project from GitHub and execute Maven-based Selenium tests as part of a continuous integration pipeline.

8. Can I use Python instead of Java for Selenium projects?

Yes. Selenium supports Python as well as Java. The choice depends on project requirements, team skills and the technology ecosystem.


Conclusion

A practical Selenium automation project is one of the best ways to develop confidence in browser automation and prepare for technical interviews.

Start with simple workflows such as login and product selection. Gradually introduce Page Object Model, Maven, TestNG, data-driven testing, reporting and CI/CD integration.

The objective should be to build a maintainable automation framework rather than simply create scripts that click through an application.

With hands-on practice and structured learning, you can develop the skills required for Automation Test Engineer and SDET roles.

No comments:

Post a Comment

TDS on Salary: A Practical Guide for HR and Payroll Professionals

  TDS on Salary: A Complete Guide for HR and Payroll Professionals Learn how TDS on salary works in India , the role of employers, employee...