DEV Community

Sourojit Das
Sourojit Das

Posted on • Originally published at browserstack.com

How to create Selenium test cases

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.

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.

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:

  1. The user navigates to the BrowserStack sign-in page.
  2. In the ’email’ field, the user enters their registered email address.
  3. The user enters the registered password.
  4. 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

Converting a Selenium Test Case to a Test Script

After configuring the system to execute test scripts, let’s 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.

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.

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.

Image description

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

Image description

`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

Image description

`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);
}
}

How to Select Test Cases for Selenium Automation

Selenium and other test automation frameworks help reduce development cycle timeframes, avoid repetitive tasks and achieve 100% 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 test cases on what they are meant to do. needing to be automated. Based on business goals and requirements, automate the following:

a.Test cases to be executed with different data sets
b.Test cases to be executed on different environments
c.Test cases to be executed for different user types
d.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.

Top comments (0)