Cucumber is a popular Behavior-Driven Development (BDD) framework used for end-to-end testing. When you combine Selenium with Cucumber, you'll end up with a robust test framework which drastically simplifies the creation of functional tests.
With Cucumber, you can describe acceptance criteria in plain language that is accessible to non-technical stakeholders, such as managers. It also provides a clear set of steps to verify these criteria. Cucumber tests can be executed through a user-friendly interface that resembles a web browser, allowing you to visualize the test process and result at each step.
There's a rich ecosystem that comes with Cucumber, with its own editor called CucumberStudio, a plugin for JIRA called Cucumber for JIRA and many more integrations.
Cucumber uses a Given-When-Then syntax, which is the corner stone of BDD test development. This is called Gherkin syntax and resembles a human-readable language. It is stored in a plaintext file with a .feature
extension.
For an example of Cucumber syntax, see the sample below:
Feature: Add product to shopping cart
# Make sure we can add an item to the cart
Scenario: User purchases an item
When the User adds an item to the cart
Then the Cart should include one more item than before
# The second example removes an item from a shopping cart
Scenario: Remove item from cart
Given the Shopping cart has at least one item
When the User removes an item from the cart
Then the Shopping cart should have one less item
Why should I use Cucumber with Selenium?
If you are a fan of BDD tests, then definitely consider Cucumber. Combined with Selenium's robust web automation capabilities, this provides a good solution for QA test-engineers and developers.
Some key reasons to use Cucumber with Selenium are included in the list below:
- Rich Ecosystem: Cucumber and Selenium both have very active communities and extensive documentation. This makes it easier to find documentation and request support if you encounter a problem or have a question.
- Cross-Functional Collaboration: Cucumber's plain-text formatting encourages collaboration between developers, QA and business people. As its syntax is easier to understand than code, it promotes sharing the test logic across everyone in your organization.
- Reusability and Modularity: Cucumber promotes the reusability of step definitions. This allows testers to create modular and maintainable test scripts. This promotes test code reusability, which benefits your entire test structure.
- Test Reporting and Analysis: Cucumber offers detailed and customizable test reports. These reports make it easier to analyze your test results and identify potential problems. As Selenium in itself lacks reporting, using Cucumber in combination with Selenium makes for a perfect combination.
Using Cucumber.JS with Selenium
CucumberJS is a JavaScript testing framework that implements the BDD principles. To get started with Javascript and Cucumber, you'll need to install the necessary NPM packages:
Once installed, you can create your first Selenium test with Cucumber. Simply create a directory features
and add a file called sample.feature
.
You can now write the test in a Gherkin formatted file:
Feature: Google can find TestingBot
Background:
Given I am on Google
Scenario: Search for a term
When I fill in "q" found by "name" with "TestingBot"
And I submit
Then I should see title "TestingBot - Google Search"
Next, you can create a hook which will take care of handling the Selenium driver:
const { Builder, Capabilities } = require("selenium-webdriver");
const { Before, After } = require("@cucumber/cucumber");
var createSeleniumSession = function(){
return new Builder().
usingServer('http://localhost:4444/wd/hub').
withCapabilities(Capabilities.chrome()).
build();
}
Before(function (scenario, callback) {
var world = this;
world.driver = createSeleniumSession();
callback();
});
After(function(scenario, callback){
this.driver.quit().then(function(){
callback();
});
});
Finally, you'll need to map the Gherkin syntax to code. You can do this by creating a step definition file in step_definitions
.
const assert = require('assert')
const { When, Then } = require("@cucumber/cucumber")
let element
When(/^I fill in "([^"]*)" found by "([^"]*)" with "([^"]*)"$/, async function (value, type, keys) {
element = await this.driver.findElement(type, value)
await this.driver.sendKeys(keys)
})
When(/^I submit$/, async function () {
element.submit()
})
Then(/^I should see title "([^"]*)"$/, async function (expectedTitle) {
let title = await this.driver.getTitle()
assert.equal(title, expectedTitle)
})
Using Cucumber with IntelliJ and Eclipse
Eclipse is a popular IDE (Integrated Development Environment), mainly used by Java developers. It offers built-in support for the most popular Java frameworks and is widely used because of its good documentation, large plugin collection and great community.
Another popular IDE is IntelliJ IDEA by Jetbrains. The IntelliJ Ultimate edition even includes built-in support for Selenium tests.
Eclipse Cucumber Example
To get started, make sure you've installed the Eclipse IDE and Java Development Kit (JDK).
You can now create a new project in Eclipse. Open Eclipse and go to File > New > Java Project.
Enter a project name (e.g., "SeleniumCucumberExample") and click Finish.
Right-click on your project in Eclipse and select Properties. Go to Java Build Path > Libraries > Classpath and click on Add External JARs. Add the Selenium WebDriver JARs. You can download them from the official Selenium website.
Similarly, add the Cucumber JARs to your project. You can download these from the Cucumber JVM page.
Gherkin example
You can now add the first feature file. Create a new file that ends with .feature with this content:
Feature: Sample Feature
Scenario: Open Google
Given I open the Google website
Then I verify the title is "Google"
Create Step Definitions
Create a package for your step definitions. Right-click on the src folder, go to New > Package, and enter a package name (for example stepDefinitions).
Inside this new package, create a new Java class for step definitions (for example SampleStepDefinitions.java
).
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import static org.junit.Assert.assertEquals;
public class SampleStepDefinitions {
WebDriver driver = new ChromeDriver();
@Given("^I open the Google website$")
public void i_open_the_Google_website() {
driver.get("https://www.google.com");
}
@Then("^I verify the title is \"([^\"]*)\"$")
public void i_verify_the_title_is(String expectedTitle) {
String actualTitle = driver.getTitle();
assertEquals(expectedTitle, actualTitle);
driver.quit();
}
}
Create Test Runner
Create another package for your test runner. Right-click on the src folder, go to New > Package, and enter a package name (for example testRunners
).
Inside the package, create a new class for the test runner (for example TestRunner.java
).
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(features = "src", glue = "stepDefinitions")
public class TestRunner {
}
Run Cucumber test in Eclipse
Right-click on the TestRunner.java
class, then select Run As > JUnit Test.
Eclipse will now execute the Cucumber scenario that you have defined. You will see the result in the console panel of Eclipse.
IntelliJ Cucumber Example
To run automated tests with Cucumber and Selenium in IntelliJ IDEA, please follow the steps below.
Install Cucumber Plugin in IntelliJ
- Open IntelliJ IDEA
- Navigate to File > Settings > Plugins
- Search for the Cucumber for Java plugin, click install
Create a New Maven Project
- Open IntelliJ IDEA
- Navigate to File > New > Project
- Choose "Maven" from the left-hand menu
- Follow the wizard to set up the Maven project.
- Add the necessary dependencies in
pom.xml
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.10.1</version>
<scope>test</scope>
</dependency>
Add Cucumber Feature Files
- Create feature files with the
.feature
extension in thesrc/test/resources
directory. - You can now write test scenarios using the Gherkin syntax
Write Cucumber Step Definitions
- Create step definition files in the
src/test/java
directory. - Write step definitions for each step in the feature files.
Create Cucumber Test Runner Class
- Create a Java class with the
@RunWith(Cucumber.class)
annotation. - Specify the path to the feature files and the location of the step definitions.
package sampleTest;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
features = "Feature", glue={"stepDefinition"}
)
public class CucumberTestRunner {
}
When you've completed all the steps, you can run your first Cucumber test through IntelliJ. Right-click on the test runner class and click Run tests.