How to create Selenium test cases
By Sourojit Das, Community Contributor - February 12, 2023
Selenium has established itself as one of the most popular automation testing frameworks within the software engineering community. Comprising a suite of tools – IDE, RC, WebDriver, and Grid – Selenium has quickly established itself as a market leader in the test automation sector.
Selenium capitalized on the inadequacies of previously used frameworks like HP QTP, and Mercury’s Astra QuickTest which compelled users to write scripts in VBScript and were primarily intended for desktop-based tests. Its support of a variety of languages like Java, Python, C#, Perl, Ruby, .net and PHP, has made it popular with individual testers and companies like Netflix, Google, HubSpot, and Fitbit among others.
The core idea behind Jason Higgins launching Selenium back in 2004 was to remove the need for users to perform repetitive manual testing. This article will focus on how to write test cases in Selenium in a way that allows us to leverage its ability to provide maximum, accurate test coverage in a limited time.
Let’s start by giving a brief outline of how test cases are written, and then proceed to create a Selenium WebDriver test script from a manual test case using the JAVA programming language.
Note: BrowserStack is now the first cloud test automation platform to announce complete support for Selenium 4, and it’s BiDi APIs. Learn More.
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:
- Can a user login with the correct user ID and password?
- What happens when an invalid email id and invalid password are entered into the form?
- What happens when a valid email id and invalid password are entered into the form?
- 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.
Example of a Test Case in Selenium
Let’s build a Selenium test case example based on the first test scenario.
- 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.’
- Prerequisites: A registered email ID with a unique username and password.
- Browser: Chrome v 86.
- Test Data: Legitimate username and password.
- Expected/Intended Results: Once username and password are entered, the web page redirects to the user’s dashboard.
- Actual Results: As Expected
- Test Status: Pass/Fail: Pass
Read More: How to write Test Cases with Examples
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), let’s convert the manual test case into an executable test script. For that, carry out the following steps:
- Create a Selenium WebDriver instance.
- Perform browser optimization if necessary.
- Write a sequence of commands to execute the test steps.
- Validate the actions performed.
Let’s 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
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.
Use the ID locator in Chrome DevTools to identify the necessary elements for the Email field, and store them in a webelement variable.
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");
Read More: SendKeys in Selenium WebDriver
Step 3 – The user enters the registered password
Repeat the same process for the password field as well
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.
Read More: Assert and Verify Methods in Selenium
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.
- Select test suites which offer the highest Return on Investment in terms of cost-saving, increasing efficiency, and improving test quality.
- 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
- 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.
Read More: Parallel Testing with Selenium
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.