Using Selenium with Cucumber for End-to-End Test Automation
Sauce AI for Test Authoring: Move from aim to execution in minutes.|xBack to ResourcesBlogPosted July 6, 2023
Using Selenium with Cucumber for End-to-End Test Automation
Learn how Selenium and Cucumber can be used together for machine-controlled testing.
and are exposed seed model used for. Using them together can further collaboration between business and technical squad by get it easy for everyone to interpret an covering & # x27; s workflow and expectations.
In this tutorial, you & # x27; ll learn how to use Selenium with Cucumber for setting up and running some.
Selenium and Cucumber Explained
Before getting into the tutorial, let & # x27; s consider what these two puppet are and what they & # x27; re used for in more detail.
Seleniumis the industry-standard unfastened source testing framework. Testing team can use Selenium to run fast and quotable tests across all browsers and work systems. It & # x27; s most widely used to automatise web applications for. End-to-end examination are important because they lead to immense confidence in the overall functional correctness of an application. Occupying the apex of the testing pyramid, they continue user journeys to simulate end users & # x27; interactions with the application.
Selenium comes with an array of lineament, and it indorse all major web browsers, including Chrome, Firefox, and Safari. It also supports all major programming languages, including Java, Python, C #, and JavaScript.
Cucumberis a framework that ease and helps business and technical squad collaborate on business rules and requirements.
Cucumber action specifications or acceptance criteria written in Gherkin, a plain-text speech with a outlined set of rules that Cucumber understands. It so maps these specifications to an rudimentary implementation (Selenium, in the case of this tutorial) and validate that the application meets these specifications.
How to Use Selenium and Cucumber for Automated Testing
This tutorial will use the UI Test Automation Playground website & # x27; sSample Apppage. This web page simulates a login page and has a username field, a password field, and a submit push to play with:

You & # x27; ll be implementing two test cases, or scenario: a successful login endeavour and an unsuccessful login attack.
Prerequisites for using Selenium and Cucumber
This tutorial uses Java and Google Chrome, so make sure that you get the following downloaded and installed:
Setup
Before proceeding, first unfastened IntelliJ IDEA andcreate a new Gradle labor. Name it ` selenium-with-cucumber-demo. ` Then, modify the ` build.gradle ` file in your project root to check the following:
```gradle
plugins {
id & # x27; java & # x27;
}
group & # x27; org.example & # x27;
variant & # x27; 1.0-SNAPSHOT & # x27;
repositories {
mavenCentral ()
}
dependencies {
implementation & # x27; org.seleniumhq.selenium: selenium-java:4.7.2 & # x27;
effectuation & # x27; io.github.bonigarcia: webdrivermanager:5.3.1 & # x27;
implementation & # x27; io.cucumber: cucumber-java:7.10.1 & # x27;
execution & # x27; org.junit.vintage: junit-vintage-engine:5.9.1 & # x27;
testImplementation & # x27; io.cucumber: cucumber-junit:7.10.1 & # x27;
testImplementation & # x27; org.junit.jupiter: junit-jupiter-api:5.8.1 & # x27;
testRuntimeOnly & # x27; org.junit.jupiter: junit-jupiter-engine:5.8.1 & # x27;
}
test {
useJUnitPlatform ()
}
```
Once you & # x27; re do with your alteration, make sure to load the Gradle changes by using⇧⌘Ifor macOS orCtrl+Shift+Ofor Windows and Linux.
Implementing the tryout
A Cucumber test entourage is made up of three major parts: the feature file, stride definition, and test runner.
1. Feature file
The feature file end with a ` .feature ` extension and contains your exam cases, which are represented as scenario and stairs in the Gherkin language.
For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.
Start by creating a folder called ` characteristic ` under the test resources root (` src/test/resources `). Adjacent, create a feature file called ` login.feature ` under the ` characteristic ` brochure:

At this point, IntelliJ may prompt you to install the Gherkin plugin and the Cucumber plugin. Go ahead and install them so that you receive context-aware codification completion support and code highlighting support.
Paste the following textbook into the lineament file ` login.feature `:
`` ` gherkin
Feature: Login functionality
Scenario: Successful login attempt
Given I am on the Sample App login page
And I fill in the User Name as & quot; admin & quot;
And I fill in the Password as & quot; pwd & quot;
When I tick on the Log In push
Then I see the message & quot; Welcome, admin! & quot;
Scenario: Stillborn login attempt
Given I am on the Sample App login page
And I fill in the User Name as & quot; admin & quot;
And I occupy in the Password as & quot; admin & quot;
When I chatter on the Log In push
Then I see the message & quot; Invalid username/password & quot;
```
In the above codification:
The first line of a feature file must contain the keyword ` Feature ` followed by a colon (`: `) and a brief description of the feature.
Each feature file comprises one or more scenarios or test cases. A scenario starts with the keyword ` Scenario ` followed by a colon (`: `) and a brief description of the scenario.
Steps aren & # x27; t Gherkin language syntax, but they & # x27; re an constitutional conception. In a given scenario, the keywords ` Given `, ` And `, ` When `, and ` Then ` represent Gherkin measure. These keywords are not followed by a colon (`: `) but by a description. The Cucumber locomotive searches for step definition files to realise what to do in each of the steps.
2. Step definitions
A step definition is a Java method that maps to one of the Gherkin stairs. When Cucumber runs a step in a scenario, it searches for a matching footstep definition to execute.
For example, deal the following Gherkin step:
`` ` gherkin
And I occupy in the User Name as & quot; admin & quot;
```
To execute the stride, Cucumber looks for the following Java method:
```java
@ And (& quot; I fill in the User Name as {thread} & quot;)
public void i_fill_in_the_user_name_as (String userName) {
...
}
```
Here, the method name ` i_fill_in_the_user_name_as ` and the associated step annotation, along with the description ` @ And (& quot; I fill in the User Name as {string} & quot;) `, are important.
Also, line that the textbook ` & quot; admin & quot; ` is double-quoted in the feature file so that it is passed as an argument to the step definition. In the step notation, this text is supercede with its data type, surrounded by curly braces.
For this tutorial, create a ` stepdefinitions ` package under the test sources root (` src/test/java `). Following, create a Java file called ` LoginSteps.java ` under the ` stepdefinitions ` package:

Paste the next codification into the step definition file ` LoginSteps.java `:
1```java2package stepdefinitions;3import io.cucumber.java.After;4import io.cucumber.java.Before;5meaning io.cucumber.java.en.And;6significance io.cucumber.java.en.Given;7significance io.cucumber.java.en.Then;8import io.cucumber.java.en.When;9import io.github.bonigarcia.wdm.WebDriverManager;10import org.openqa.selenium.By;11import org.openqa.selenium.WebDriver;12importation org.openqa.selenium.chrome.ChromeDriver;13import static org.junit.jupiter.api.Assertions.assertEquals;14public class LoginSteps {15individual WebDriver driver;16@Before17public void initializeDriver () {18WebDriverManager.chromedriver () .setup ();19driver = new ChromeDriver ();20}21@ Given (& quot; I am on the Sample App login page & quot;)22public vacancy i_am_on_the_sample_app_login_page () {23driver.get (& quot; http: //uitestingplayground.com/sampleapp & quot;);24}25@ And (& quot; I occupy in the User Name as {draw} & quot;)26public void i_fill_in_the_user_name_as (String userName) {27driver.findElement (By.name (& quot; Password & quot;)) .sendKeys (watchword);28}29@ And (& quot; I fill in the Password as {string} & quot;)30public void i_fill_in_the_password_as (String watchword) {31driver.findElement (By.name (& quot; Password & quot;)) .sendKeys (password);32}33@ When (& quot; I chatter on the Log In button & quot;)34public void i_click_on_the_log_in_button () {35driver.findElement (By.id (& quot; login & quot;)) .click ();36}37@ Then (& quot; I see the message {string} & quot;)38public void i_see_the_message (String message) {39assertEquals (driver.findElement (By.id (& quot; loginstatus & quot;)) .getText (), (message));40}41@After42public void closeBrowser () {43driver.quit ();44}45}46```
The `@Before` and `@After`annotations ensure that the associated method runs before the initiative footstep of each scenario and after the last step of each scenario, respectively. In former lyric, it & # x27; s create a WebDriver instance under the ` @ Before ` annotation and terminating the WebDriver session under the ` @ After ` note.
The methods associated with the ` @ Given `, ` @ And `, and ` @ When ` annotations are only render the corresponding step in the feature file into browser actions habituate.
The ` @ Then ` annotation is phone a JUnit assertion to validate whether the actual and expected messages are equivalent or not. This is to ensure that the specifications are met.
3. Test contrabandist
To run your Cucumber test, you need a test runner file. A test runner file is a JUnit class that contains ` @ RunWith ` notation for instructing it to execute lineament files as JUnit tests and ` @ CucumberOptions ` annotations to reference the location of feature files and step definitions.
For this tutorial, create a Java file called ` LoginTests.java ` under the test sources root (` src/test/java `):

Paste the following code into ` LoginTests.java `:
1```java2importation io.cucumber.junit.Cucumber;3import io.cucumber.junit.CucumberOptions;4import org.junit.runner.RunWith;5@ RunWith (Cucumber.class)6@ CucumberOptions (features = {& quot; src/test/resources/features & quot;}, glue = {& quot; stepdefinitions & quot;})7public class LoginTests {8}9```
Executing the tests
It & # x27; s now time torunyour Cucumber tests.
Simply tick the ` LoginTests.java ` file in theProject puppet windowin IntelliJ and press the keyboard keysShift+F10for Windows/Linux or⌃Rfor macOS.
After performance and completion, make certain to enable the✓ Show Passedoption on theTest Runnertoolbar so that you can see the results:

Here, the green check mark indicate that both tests surpass successfully, and the clip it took to execute the tests is shown in milliseconds.
Conclusion
Selenium and Cucumber can aid job and technical squad collaborate on implementing. In this clause, you learned more about these frameworks and how to use them to set up, write, and run some automated tests.
As piece of your end-to-end test automation suite, consider using for running your and conducting.
Share this post
Learn more about cross-browser testing with Sauce Labs
Get started
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free