Selenium is an open-source tool for automating web applications across different browsers. It supports multiple programming languages like Java, Python, C#, Ruby, and JavaScript, making it a popular choice for testers worldwide.
Hereβs a simple Java Selenium script that will open Google and search for βSeleniumβ:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FirstSeleniumScript {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("Selenium");
driver.findElement(By.name("q")).submit();
System.out.println("Page Title is: " + driver.getTitle());
driver.quit();
}
}
driver.quit()
You can practice Selenium on this sample site: OrangeHRM Demo
Locators help Selenium identify elements on a web page to perform actions like click, type, or verify. They are critical for any Selenium automation script.
// By ID
driver.findElement(By.id("username")).sendKeys("admin");
// By Name
driver.findElement(By.name("password")).sendKeys("admin123");
// By Class Name
driver.findElement(By.className("submit-btn")).click();
// By Tag Name
List<WebElement> inputs = driver.findElements(By.tagName("input"));
// By Link Text
driver.findElement(By.linkText("Forgot Password?")).click();
// By Partial Link Text
driver.findElement(By.partialLinkText("Forgot")).click();
// By CSS Selector
driver.findElement(By.cssSelector("input[type='text']")).sendKeys("sample");
// By XPath
driver.findElement(By.xpath("//button[@type='submit']")).click();
Try identifying these elements on the sample demo website: OrangeHRM Demo.
id="txtUsername"
id="txtPassword"
id="btnLogin"
Use these locators in your practice scripts to automate login functionality.
XPath stands for XML Path Language. It is a powerful way to navigate through HTML or XML elements to locate them precisely. Selenium uses XPath to find dynamic elements on web pages.
/html/body/div[1]/form/input
//input[@id='username']
//tagname[@attribute='value']
β find a tag by attribute//tagname[text()='text']
β find a tag with exact text//tagname[contains(@attribute,'partial')]
β partial match//div[@class='container']//a
β nested elements
// absolute example
driver.findElement(By.xpath("/html/body/div/form/input")).sendKeys("hello");
// relative example
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin");
// contains()
driver.findElement(By.xpath("//button[contains(text(),'Login')]")).click();
// text()
driver.findElement(By.xpath("//h1[text()='Dashboard']")).isDisplayed();
//button[@type='submit' and contains(text(),'Login')]
Try finding elements on the OrangeHRM demo:
//input[@id='txtUsername']
//input[@id='txtPassword']
//input[@id='btnLogin']
The Selenium Actions
class helps you handle advanced user interactions such as mouse hover, drag and drop, double click, right click, and more. These are often needed for modern web applications with dynamic behavior.
import org.openqa.selenium.interactions.Actions;
WebDriver driver = new ChromeDriver();
Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.id("menu"));
actions.moveToElement(menu).perform(); // mouse hover
actions.contextClick(menu).perform(); // right click
actions.doubleClick(menu).perform(); // double click
WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
actions.dragAndDrop(source, target).perform();
.perform()
at the end of an Actions chainTry practicing mouse hover or drag-and-drop on:
A dropdown (or select element) lets users choose one or more options from a list. In Selenium, dropdowns can be handled using the Select
class in Java.
Selenium provides a built-in Select
class that works with HTML <select>
tags.
import org.openqa.selenium.support.ui.Select;
WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
// select by visible text
select.selectByVisibleText("India");
// select by index
select.selectByIndex(2);
// select by value attribute
select.selectByValue("US");
if(select.isMultiple()) {
select.selectByVisibleText("Option1");
select.selectByVisibleText("Option2");
}
isMultiple()
for multi-select dropdownsTry practicing on a sample site: Guru99 Register Demo
An alert is a small popup window that displays a message or asks for confirmation (like JavaScript alerts, confirms, or prompts). Selenium can handle alerts using its built-in Alert
interface.
Alert alert = driver.switchTo().alert();
// accept the alert
alert.accept();
// dismiss (if confirm box)
alert.dismiss();
// get alert text
String msg = alert.getText();
// send text to a prompt
alert.sendKeys("sample text");
getText()
You can try practice alerts here: DemoQA Alerts
Web pages often load elements dynamically, so actions might fail if Selenium tries to interact before elements are ready. Waits help synchronize your tests with the application to avoid flakiness.
// Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Explicit wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
// Fluent wait
Wait fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement foo = fluentWait.until(driver -> driver.findElement(By.id("foo")));
Try testing waits on dynamic elements at: Herokuapp Dynamic Loading
TestNG is a popular testing framework for Java that makes it easier to organize, execute, and report Selenium tests. It supports annotations, parallel execution, groups, priorities, and data-driven testing.
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
public class LoginTest {
@BeforeClass
public void setup() {
System.out.println("Open Browser");
}
@Test
public void login() {
System.out.println("Perform Login");
}
@AfterClass
public void tearDown() {
System.out.println("Close Browser");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="MySuite">
<test name="MyTest">
<classes>
<class name="LoginTest"/>
</classes>
</test>
</suite>
You can practice running TestNG tests in Eclipse or IntelliJ by installing the TestNG plugin from the marketplace.
DataProvider is a feature in TestNG that allows you to pass multiple sets of data to a single test method. This helps build data-driven tests without duplicating code.
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class LoginDataTest {
@DataProvider(name = "loginData")
public Object[][] getData() {
return new Object[][] {
{"admin", "admin123"},
{"user", "user123"},
{"guest", "guest123"}
};
}
@Test(dataProvider = "loginData")
public void loginTest(String username, String password) {
System.out.println("Logging in with: " + username + " / " + password);
}
}
Practice creating a DataProvider for a login test on: OrangeHRM Demo
Parameterization means passing different input values to your test scripts without hardcoding them, making your tests reusable and data-driven.
<parameter>
tags in XML
// testng.xml
<parameter name="username" value="admin"/>
// Java
@Parameters({"username"})
@Test
public void testLogin(String user) {
System.out.println("Logging in with: " + user);
}
// simplified example
FileInputStream fis = new FileInputStream("testdata.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet("Login");
String username = sh.getRow(0).getCell(0).getStringCellValue();
Try parameterizing login data for OrangeHRM Demo with different usernames and passwords.
The Page Object Model (POM) is a design pattern in Selenium that helps you maintain clean, reusable, and scalable test code by separating page locators and actions into dedicated classes.
Letβs automate a simple login page.
// LoginPage.java
public class LoginPage {
WebDriver driver;
@FindBy(id="username") WebElement usernameField;
@FindBy(id="password") WebElement passwordField;
@FindBy(id="loginBtn") WebElement loginButton;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void login(String user, String pass) {
usernameField.sendKeys(user);
passwordField.sendKeys(pass);
loginButton.click();
}
}
Then in your test class:
// LoginTest.java
LoginPage lp = new LoginPage(driver);
lp.login("admin", "admin123");
pages
, tests
)Try implementing POM for the login flow of OrangeHRM Demo.
A Hybrid Framework combines multiple automation frameworks such as Data-Driven, Keyword-Driven, and Page Object Model. It takes the best features of each and creates a flexible, scalable, and reusable structure for automation.
Typically, a Hybrid Framework has:
/tests
LoginTest.java
/pages
LoginPage.java
/keywords
KeywordLibrary.java
/utils
ExcelUtils.java
/testdata
LoginData.xlsx
/reports
extent-report.html
Try building a hybrid framework combining DataProvider, POM, and reusable keyword methods for: OrangeHRM Demo.
Behavior Driven Development (BDD) is a software development approach where test scenarios are written in plain English using a language called Gherkin. BDD bridges the gap between business, development, and testing teams by making test cases more readable and collaborative.
Feature: Login functionality
Scenario: Successful login
Given user is on login page
When user enters valid credentials
Then user should be redirected to the dashboard
@Given("user is on login page")
public void user_is_on_login_page() {
driver.get("https://opensource-demo.orangehrmlive.com/");
}
@When("user enters valid credentials")
public void user_enters_valid_credentials() {
driver.findElement(By.id("txtUsername")).sendKeys("Admin");
driver.findElement(By.id("txtPassword")).sendKeys("admin123");
driver.findElement(By.id("btnLogin")).click();
}
@Then("user should be redirected to the dashboard")
public void user_should_see_dashboard() {
Assert.assertTrue(driver.findElement(By.id("welcome")).isDisplayed());
}
Try writing a login feature and step definition for OrangeHRM Demo using Cucumber and Selenium.
Jenkins is an open-source continuous integration and continuous delivery (CI/CD) tool that helps automate building, testing, and deploying software. It integrates perfectly with Selenium frameworks to automatically run your automated tests.
http://localhost:8080
mvn clean test
Try configuring a Jenkins Freestyle job to run your Selenium Maven project after each code commit from GitHub.
GitHub is a powerful version control and collaboration platform that helps you store, share, and manage your Selenium automation code with teams. It allows you to track changes, manage branches, and integrate with CI/CD tools like Jenkins.
git
commands or GitHub Desktop to push your project code
git init
git add .
git commit -m "first selenium project"
git remote add origin https://github.com/yourusername/yourrepo.git
git push -u origin main
Create a GitHub repo, push your Selenium Maven project, and link it to a Jenkins build pipeline.
Maven is a popular build automation and dependency management tool for Java projects. It makes it easy to manage Selenium libraries, build processes, and test execution from a single configuration file.
pom.xml
to manage everythingbin
directory to your system PATHmvn -v
in your terminalpom.xml
for Selenium
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>seleniumproject</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Use the following command to execute tests:
mvn clean test
pom.xml
clean and organizedCreate a Maven project for Selenium and configure it to run TestNG tests automatically.
Reports help you visualize test execution results, identify failures quickly, and share outcomes with your team or stakeholders. Selenium alone does not generate rich reports, so you typically integrate it with reporting tools.
// Maven dependency
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.1.0</version>
</dependency>
// Java example
ExtentReports extent = new ExtentReports();
ExtentSparkReporter spark = new ExtentSparkReporter("target/Spark.html");
extent.attachReporter(spark);
ExtentTest test = extent.createTest("LoginTest");
test.pass("Login test passed");
extent.flush();
Try setting up ExtentReports for your Selenium TestNG project to generate detailed reports with pass/fail screenshots.
Letβs put everything together in a simple Selenium Maven + TestNG project following POM design pattern. Weβll automate login for the OrangeHRM demo site as a practical example.
/src
/main
/java
/pages
LoginPage.java
/tests
LoginTest.java
/utils
ExcelUtils.java
/testdata
LoginData.xlsx
/testng.xml
public class LoginPage {
WebDriver driver;
@FindBy(id="txtUsername") WebElement username;
@FindBy(id="txtPassword") WebElement password;
@FindBy(id="btnLogin") WebElement loginButton;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void login(String user, String pass) {
username.sendKeys(user);
password.sendKeys(pass);
loginButton.click();
}
}
public class LoginTest {
WebDriver driver;
LoginPage login;
@BeforeClass
public void setup() {
driver = new ChromeDriver();
driver.get("https://opensource-demo.orangehrmlive.com/");
login = new LoginPage(driver);
}
@Test
public void testLogin() {
login.login("Admin", "admin123");
Assert.assertTrue(driver.findElement(By.id("welcome")).isDisplayed());
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
<suite name="OrangeHRMSuite">
<test name="LoginTest">
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>
Enhance this project by adding DataProviders, external data sources, and Jenkins for CI/CD.