Selenium is widely loved by web testers around the world thanks to its versatility and simplicity. Testing with Selenium is quite straightforward, which is why it is commonly used for people who want to go from manual to automation testing.
In this article, we will show you how to write Selenium test cases the right way.
Achieving 100% test coverage sounds amazing. However, that figure is almost impossible to reach, considering that most teams have resource and time constraints on their testing projects. Testers should instead aim to test what their business requires.
From here arises another challenge: the tres amigos (three friends) in software development don’t always share the same perspective. The tres amigos are:
Now we need to establish a common ground between them. Instead of going the traditional way where they discuss their plans in three different languages, the tres amigos use a shared language: Gherkin. It is structured by three primary statements: Given, When, and Then, with each statement describing a specific aspect of the system:
Learn more: What is BDD Testing?
For example, after discussion, the team arrives at this Gherkin file:
Feature: Online Order Placement and Status Updates
As a customer,
I want to be able to place an online order for products,
And receive real-time updates on the status of my order.
We can easily come up with 10 test cases for it:
Test Case 1: Place an Online Order Successfully
Test Case 2: Receive Real-Time Order Status Updates
Test Case 3: Invalid Payment Information
Test Case 4: Verify Order History After Placement
Test Case 5: Cancel an Order
Test Case 6: Receive Email Confirmation After Order Placement
Test Case 7: Update Shipping Information Before Order Is Shipped
Test Case 8: Apply Discount Code During Checkout
Test Case 9: Verify Order Status Change Notifications
Test Case 10: Place an Order as a Guest User
To effectively use Selenium, you should have a basic understanding of at least one programming language. Popular choices include Java, Python, C#, and Ruby. Familiarity with programming concepts such as variables, loops, conditionals, and functions is essential.
Additionally, ensure you understand the basics of web technologies:
Prepare your integrated development environment (IDE). Popular IDEs for Selenium include:
After that, install Selenium from its official website. Make sure to also install the WebDriver for the browser you want to test on.
Now you’re ready to write your Selenium test case.
Let’s start testing on the Facebook login page.
Your test case should look like this:
Test Case ID | TC_FB_001 |
Title | Facebook Login with Valid Credentials |
Objective | Verify that a user can log in to Facebook with valid credentials. |
Preconditions | - Chrome WebDriver is installed. - Selenium is set up. - Valid Facebook credentials are available. |
Test Steps | 1. Launch Chrome using ChromeDriver. 2. Go to the Facebook login page. 3. Type valid email/phone and password into the login fields. 4. Click Log in. 5. Verify that the user is on the Facebook home or profile page. 6. Close browser. |
Expected Results | Users should be redirected to the Facebook home or profile page and see login-related elements (e.g., profile picture). |
Actual Results | (To be filled after test execution.) |
Status | (To be filled after test execution, e.g., Passed/Failed.) |
Comments | (Any additional comments or observations.) |
Let’s start testing!
First, import the necessary libraries. Here we need ChromeDriver to control Google Chrome. The ChromeOptions statement is needed to run in headless mode where you don’t need to load the GUI for better performance.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
Next, set up the path to the ChromeDriver executable in your machine.
public class FacebookLoginTest { public static void main(String[] args) { // Path to your ChromeDriver executable System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
Now we can configure ChromeOptions to run in headless mode.
ChromeOptions options = new ChromeOptions(); options.addArguments("--headless"); // Run in headless mode (no GUI)
Initialize the WebDriver:
WebDriver driver = new ChromeDriver(options);
Use driver.get(url) to navigate to the URL you want. In our case, it is https://facebook.com.
try {
driver.get("https://www.facebook.com");
After that, right-click on the Facebook email field and choose Inspect. You should find the ID for it. Selenium will base on this ID to locate the field and fill in the information.
Similarly, do the same for the password field:
Now locate the elements:
WebElement emailField = driver.findElement(By.id("email"));
WebElement passwordField = driver.findElement(By.id("pass"));
Use sendKeys to add your email and password to it:
emailField.sendKeys("your_email@example.com");
passwordField.sendKeys("your_password");
Do the same to locate the login button. Upon inspecting, we see its ID is “login.” We can use the click() method to perform the action:
WebElement loginButton = driver.findElement(By.name("login"));
loginButton.click();
Wait for the page to load:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
WebElement profilePicture = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("img[aria-label='Profile picture']")));
System.out.println("Test Passed: User is on the Facebook home/profile page.");
} catch (Exception e) {
System.out.println("Test Failed: User is not on the Facebook home/profile page.");
}
Here we implement three methods:
Once done, close the browser:
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
Here’s our full code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class FacebookLoginTest {
public static void main(String[] args) {
// Path to your ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
// Set up Chrome options
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless"); // Run in headless mode (no GUI)
// Initialize the Chrome WebDriver
WebDriver driver = new ChromeDriver(options);
try {
// Step 1: Launch Chrome using ChromeDriver
driver.get("https://www.facebook.com");
// Step 2: Go to Facebook Login Page
// Already on the Facebook login page
// Step 3: Type valid email/phone and password into the login fields
WebElement emailField = driver.findElement(By.id("email"));
WebElement passwordField = driver.findElement(By.id("pass"));
// Replace these with valid credentials
emailField.sendKeys("your_email@example.com");
passwordField.sendKeys("your_password");
// Step 4: Click Log In
WebElement loginButton = driver.findElement(By.name("login"));
loginButton.click();
// Step 5: Verify that the user is on the Facebook home or profile page
// Use WebDriverWait to wait until the profile picture is visible
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
WebElement profilePicture = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("img[aria-label='Profile picture']")));
System.out.println("Test Passed: User is on the Facebook home/profile page.");
} catch (Exception e) {
System.out.println("Test Failed: User is not on the Facebook home/profile page.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Step 6: Close Browser
driver.quit();
}
}
}