Cucumber Basics: A Beginner's Guide
Introduction to Cucumber Cucumber is a powerful tool for Behavior-Driven Development (BDD)
that enables teams to write tests in plain English using the Gherkin language. It helps bridge the
communication gap between business stakeholders and developers.
Why Use Cucumber?
• Improves collaboration between teams
• Uses human-readable language (Gherkin)
• Supports multiple programming languages like Java, Python, and JavaScript
• Integrates with testing frameworks like JUnit and TestNG
Key Cucumber Concepts
1. Feature File - Contains test scenarios written in Gherkin.
2. Scenario - A specific test case written in plain language.
3. Step Definition - The implementation of test steps in code.
4. Tags - Used to organize and filter test scenarios.
5. Hooks - Code that runs before or after scenarios (e.g., setup/teardown).
6. Runner Class - Executes Cucumber tests using a test framework.
Installing Cucumber (Java Example) Cucumber can be used with Java by adding dependencies to
a Maven or Gradle project.
For Maven, add the following to your pom.xml:
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.0.0</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>7.0.0</version>
</dependency>
</dependencies>
Writing a Basic Feature File Create a login.feature file:
Feature: Login Functionality
Scenario: Successful login with valid credentials
Given the user is on the login page
When the user enters valid username and password
Then the user should be redirected to the homepage
Creating Step Definitions (Java Example)
import io.cucumber.java.en.*;
public class LoginSteps {
@Given("the user is on the login page")
public void userOnLoginPage() {
System.out.println("User is on login page");
}
@When("the user enters valid username and password")
public void enterValidCredentials() {
System.out.println("User enters valid credentials");
}
@Then("the user should be redirected to the homepage")
public void userRedirectedToHomepage() {
System.out.println("User is redirected to homepage");
}
}
Running Cucumber Tests Create a test runner using JUnit:
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(features="src/test/resources/features", glue="stepDefinitions")
public class TestRunner {}
Run the test using:
mvn test
Conclusion Cucumber simplifies test automation by using human-readable scenarios. By
integrating it with frameworks like JUnit and TestNG, you can efficiently test web applications and
APIs.
Happy Testing!