Writing Your First Selenium Test Case Using Java
Writing Your First Selenium Test Case Using Java
✅ Step 1: Set Up Your Environment
Requirements
Java JDK (Java Development Kit)
An IDE (e.g., IntelliJ IDEA, Eclipse)
Maven (for dependency management)
Selenium WebDriver
A browser driver (e.g., ChromeDriver)
Maven Project Setup
Create a new Maven project and add this to your pom.xml:
xml
Copy
Edit
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.21.0</version>
</dependency>
</dependencies>
(Use the latest version from the official Maven repository).
✅ Step 2: Download Browser Driver
For example, if you're using Chrome:
Go to: https://chromedriver.chromium.org/downloads
Download the version that matches your browser
Extract and place it in a known location
You can also set the path programmatically in code (explained below).
✅ Step 3: Write Your First Test Case
Here's a basic test case that:
Launches Chrome
Opens Google
Searches for “Selenium WebDriver”
Prints the title of the results page
java
Copy
Edit
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FirstSeleniumTest {
public static void main(String[] args) {
// Set path to chromedriver
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
// Open Google
driver.get("https://www.google.com");
// Accept cookies if prompt appears (optional)
// WebElement acceptButton = driver.findElement(By.id("L2AGLb"));
// acceptButton.click();
// Locate search box, type query, and submit
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Selenium WebDriver");
searchBox.submit();
// Wait for the results to load (simple sleep for demo; better to use WebDriverWait)
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Print the title of the page
System.out.println("Page Title: " + driver.getTitle());
// Close the browser
driver.quit();
}
}
✅ Step 4: Run the Test
Run your Java class.
You should see a browser pop up, navigate to Google, perform the search, and close.
π§ Tips
For real test cases, use WebDriverWait instead of Thread.sleep() for reliability.
Use a test framework like JUnit or TestNG for managing multiple tests.
Selenium Grid can help you run tests across multiple browsers and environments.
Learn Selenium JAVA Course
Read More
Setting Up Selenium WebDriver in Java: A Step-by-Step Guide
Which is the best IT Training Selenium With Java course in Hyderabad?
Visit Our IHUB Talent Training in Hyderabad
Comments
Post a Comment