How to create Selenium test cases

Master the essentials of writing robust Selenium test cases to boost test efficiency and catch bugs early in the cycle.

Guide Banner Image
Home Guide How to create Selenium test cases

How to create Selenium test cases

Selenium is one of the most widely used tools for automating web application testing across browsers and platforms.

Writing effective Selenium test cases involves identifying the right user flows, selecting locators, implementing test logic, and ensuring maintainability through best practices. Whether you’re testing a login page or a complete checkout flow, structured Selenium tests help catch bugs early and improve test coverage in CI/CD pipelines.

This guide walks you through the step-by-step process of writing, organizing, and executing Selenium tests to ensure reliable and scalable browser automation.

How to extract test cases from Business Requirements

All software must undergo End to End testing before being released. This method tests the application workflow from beginning to end by replicating different user scenarios. The first step in performing an End to End test is to analyze business requirements. A tester considers the different user personas involved, aims for maximum test coverage, and considers using automation to achieve it.

The usual process starts with the tester studying the business requirements to isolate a set of user stories. These user stories help represent the business requirements – what a person using the product would like to be able to do. This, in turn, helps cater to a series of user personas, and create a number of test scenarios.

Once the test scenarios are framed, a set of industry-wide best practices are followed to frame these scenarios into a sequence of actions that can help verify a particular functionality. This is what is known as a Test Case.

Writing a test case using Selenium

To write the first test case, consider a sample business requirement – Ensure secure user entry to a Browserstack Account.

Given that a user trying to gain entry to a Browserstack Account could either be a new or an existing user, test scenarios can be framed around both the Register and Login pages.

For the purposes of this article, consider the user persona to be that of a registered user.

On viewing encounter the Browserstack Login page, ask the following questions:

  1. Can a user login with the correct user ID and password?
  2. What happens when an invalid email id and invalid password are entered into the form?
  3. What happens when a valid email id and invalid password are entered into the form?
  4. What happens when an invalid email id and valid password are entered into the form?

All of these test scenarios can now be expanded into a set of positive and negative test cases.

Positive test cases ensure that the ‘happy-path’ or expected user journey when the correct data is entered, works as intended. Negative test cases focus on invalid actions, often by replicating the input of invalid data or seeking access to an invalid component.

In this case, the first test scenario can lead to the development of a positive test case, whereas the rest lead to negative test cases.

Starting out with Selenium testing? Try BrowserStack Test University and get access to real devices for a hands-on learning experience. Get Certified for Free.

BrowserStack Automate Banner

Example of a Test Case in Selenium

Build a Selenium test case example based on the first test scenario.

1. Test Scenario: To authenticate a successful user login on Browserstack.com

Test Steps:

  • The user navigates to the BrowserStack sign-in page.
  • In the ’email’ field, the user enters their registered email address.
  • The user enters the registered password.
  • The user clicks ‘Sign Me In.’

2. Prerequisites: A registered email ID with a unique username and password.

3. Browser: Chrome v 86.

4. Test Data: Legitimate username and password.

5. Expected/Intended Results: Once username and password are entered, the web page redirects to the user’s dashboard.

6. Actual Results: As Expected

7. Test Status: Pass/Fail: Pass

Converting a Selenium Test Case to a Test Script

After configuring the system to execute test scripts (as discussed in a previous article on Selenium with Java), convert the manual test case into an executable test script. For that, carry out the following steps:

  1. Create a Selenium WebDriver instance.
  2. Perform browser optimization if necessary.
  3. Write a sequence of commands to execute the test steps.
  4. Validate the actions performed.

Explore each step in detail:

Step 1 – To launch the website in a browser of your choosing, set the system properties to the path of the required driver for the browser. Since this example uses Google Chrome, it should be set to the ChromeDriver. The code for the same is as follows –

Webdriver driver = new ChromeDriver();

System.setProperty("webdriver.chrome.driver", "Path of the chrome driver");

Step 2 – Proceed to maximize the browser for a clear picture of test cases being executed using the following command.

driver.manage.window.maximize();

Step 3 – Once the basic tasks are complete, execute each step of the manual test case articulated in the previous section.

Try Selenium Testing on Real Browsers 

Implement test steps

Here is a step-by-step procedure to implement a Selenium test script:

Step 1 The user navigates to Gmail.com

driver.get("https://www.browserstack.com/users/sign_in");

Step 2  In the ’email’ field, the user enters their registered email address.

To perform this step, locate the email field on the Google Sign In form, and enter the requisite data.

BrowserStack Sign in

Use the ID locator in Chrome DevTools to identify the necessary elements for the Email field, and store them in a webelement variable.

Use the ID locator in Chrome DevTools to identify the necessary elements for the Email field

driver.findElement(By.id("user_email_login"));

WebElement username=driver.findElement(By.id("user_email_login"));

Once the element has been located, perform the requisite action:

username.sendKeys("abc@gmail.com");

Step 3 –  The user enters the registered password

Repeat the same process for the password field as well

The user enters the registered password

driver.findElement(By.id("user_password"));

WebElement password=driver.findElement(By.id("user_password"));

password.sendKeys("your_password");

Step 4 – The user clicks ‘Sign In’

Once the email and password web elements have been located and the actions have been performed, the tester can perform the final desired action. In this case, the user clicks ‘Sign In.’

login.click();

Now, validate the actions performed using assertions. Assertions help testers compare the expected and actual results of the actions performed. If these are in sync, the test case is said to have passed. Otherwise, the test case is considered to have failed.

The assertion, in this case, is of the general form:

Assert.assertEquals(String actual, String expected);

The String actual variable holds the post-login value, which is:

String actualUrl="https://live.browserstack.com/dashboard";

The method below can help get the expected URL:

String expectedUrl= driver.getCurrentUrl();

Thus, the final code will look something like this:

Assert.assertEquals(actualUrl, expectedUrl);

If the test case passes, it will retrieve the same else will return as having failed.

The final code will be as follows:

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.Test;

public class LoginAutomation {

@Test

public void login() {

System.setProperty("webdriver.chrome.driver", "path of driver");

WebDriver driver=new ChromeDriver();

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

driver.get("https://www.browserstack.com/users/sign_in");

WebElement username=driver.findElement(By.id("user_email_Login"));

WebElement password=driver.findElement(By.id("user_password"));

WebElement login=driver.findElement(By.name("commit"));

username.sendKeys("abc@gmail.com");

password.sendKeys("your_password");

login.click();

String actualUrl="https://live.browserstack.com/dashboard";

String expectedUrl= driver.getCurrentUrl();

Assert.assertEquals(expectedUrl,actualUrl);

}

}

Run Selenium Tests on Real Device Cloud

How to Select Test Cases for Selenium Automation

Selenium and other test automation frameworks help reduce development cycle timeframes, avoid repetitive tasks and achieve maximum test coverage in a quick and efficient manner. But, to get the most out of Selenium tests, it is necessary to focus on some best practices when selecting test cases for automation.

1. Select test suites which offer the highest Return on Investment in terms of cost-saving, increasing efficiency, and improving test quality.

2. Identify Selenium test cases on what they are meant to do. needing to be automated. Based on business goals and requirements, automate the following:

  • Test cases to be executed with different data sets
  • Test cases to be executed on different environments
  • Test cases to be executed for different user types
  • Test cases that have multiple dependencies, etc

3. Consider the execution time and testing frequency of these test cases. If one or both of these parameters are high, then it is likely a test automation framework is required to write these test cases.

Teams can leverage real device cloud based platforms like BrowserStack that offer a Cloud Selenium Grid of 3000+ real browsers and devices. It empowers teams to run concurrent Selenium tests on desired real device-browser combinations online. Without the limitations of emulators and simulators, testers can verify website functionality in real user conditions. They can accelerate testing time with parallel testing, and get results faster without compromising on accuracy.

On BrowserStack, testers can leverage integrations with a host of CI/CD tools like Jenkins, Travis, Circle CI, etc. They can also utilize multiple features for more comprehensive testing scenarios – Geolocation Testing, Network Simulation, Testing on dev environments.

Talk to an Expert

Best Practices for Writing Selenium Test Cases

Following best practices ensures your Selenium test cases are reliable, maintainable, and efficient. Here are the key guidelines:

  1. Use Clear and Consistent Naming Conventions: Name your test methods and variables clearly so they reflect the purpose of the test, e.g., testLoginWithValidCredentials.
  2. Keep Tests Independent: Ensure each test case can run independently without relying on the outcome of others. This avoids cascading failures.
  3. Avoid Hardcoded Values: Use configuration files or environment variables for test data, URLs, credentials, and timeouts.
  4. Use Explicit Waits Instead of Thread.sleep(): Implement WebDriver’s explicit waits to wait for elements, reducing flakiness and improving execution speed.
  5. Centralize Locators with the Page Object Model (POM): POM promotes reuse and simplifies maintenance by storing element locators and methods in separate page classes.
  6. Validate Outcomes with Assertions: Use strong, meaningful assertions to verify application behavior after each user action.
  7. Log Test Steps and Results Clearly: Add logging at key steps to aid in debugging and traceability during test failures.
  8. Handle Exceptions Gracefully: Use try-catch blocks or test frameworks’ built-in exception handling to log errors and keep the test suite running.
  9. Run Tests Across Browsers and Devices: Test on real browsers and devices using tools like BrowserStack Automate to ensure true cross-platform compatibility.
  10. Integrate with CI/CD Early: Automate test runs as part of your deployment pipeline to catch regressions quickly.

Conclusion

Running Selenium tests effectively is key to achieving reliable, scalable, and repeatable test automation for your web applications. By setting up the right environment, choosing suitable browsers and platforms, and integrating with CI/CD pipelines, teams can ensure faster feedback and higher test coverage.

Start small, automate critical user flows first, and scale confidently using tools like BrowserStack Automate for real device and cross-browser testing.

Try BrowserStack Automate

Tags
Automation Testing Selenium Selenium Webdriver