top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

Cucumber Tutorial

Introduction

This Cucumber tutorial will help you master Behavior-Driven Development (BDD) with Cucumber. We'll travel through the complex networks of features and scenarios, learning how to express requirements using the Gherkin syntax. In this Cucumber tutorial, we'll delve into the world of step definitions, where the magic of automation is expertly orchestrated, turning scenarios into tests that can be executed.

Practical cucumber testing examples will help you understand the concepts as we move through the tutorial, connecting theory with real-world application.

Overview

This Cucumber tutorial provides an in-depth examination of Behavior-Driven Development (BDD) using Cucumber as a lens. Cucumber is a potent tool that enables communication between technical and non-technical stakeholders in software testing. The intricacies of Cucumber testing are explored in detail, along with its user-friendly Gherkin syntax and a variety of useful features. We guide learners through the process with real-world examples, from creating human-readable scenarios to turning them into tests that can be executed.

What is Cucumber Testing?

Before jumping into Cucumber testing, let’s check what is Cucumber. Cucumber is an open-source software testing tool. Cucumber testing is a methodology and framework for implementing Behavior-Driven Development (BDD) practices in software testing. It employs a human-readable syntax called Gherkin to define features, scenarios, and steps in a format that is both understandable to non-technical stakeholders and executable by automation tools.

Let's break down the key components of Cucumber testing with examples:

1. Feature:
A feature represents a specific functionality or behavior of the software that is being tested. It is described using the ‘Feature’ keyword and is followed by a brief description.

Example:

2. Scenario:
A scenario is a specific test case that illustrates a particular behaviour of the software. It is described using the Scenario keyword and is followed by a brief description.

Example:

3. Steps:
Steps are the individual actions or verifications that constitute a scenario. They are written using keywords like 'Given', 'When', 'Then', 'And', and 'But'.

Example:

4. Step Definitions:
Step definitions are the code implementations that match the Gherkin steps with the actual automation logic. They link the natural language steps to the corresponding actions in the code.

Example (Step Definition in Java using Cucumber with Selenium WebDriver):

@Given("^the user is on the login page $") 
public void userIsOnLoginPage() { 
// Code to navigate to the login page 
} 

@When("^the user enters valid credentials $") 
public void userEntersValidCredentials() { 
// Code to enter valid username and password 
} 

@And ( " ^ clicks the \ " Login \ " button $ " ) 
public void userClicks LoginButton ( ) { 
// Code to click the login button 
} 

@Then("^the user should be redirected to the dashboard $") 
public void userRedirected ToDashboard() { 
// Code to verify that the dashboard page is displayed 
}

Cucumber testing fosters collaboration among team members using Gherkin syntax. Step definitions are implemented by automation engineers to automate scenarios and validate software behavior.

What is BDD?

Behavior-Driven Development (BDD) is a software development methodology that emphasizes collaboration between technical and non-technical stakeholders to improve communication, understanding, and the overall quality of software. It extends the principles of Test-Driven Development (TDD) by focusing on the behavior of the software from the user's perspective. It involves writing tests in a human-readable format that can be easily understood by all team members, not just developers, and then automating those to verify the software's behavior.


Working of BDD With an Example:

1. Collaboration:
BDD encourages collaboration among different roles—business analysts, developers, testers, and product owners. Together, they define the expected behavior of the software using a common language.

2. Writing Scenarios:
Scenarios are written in a natural language format, using a syntax called Gherkin, that describes the behavior of the software.

3. Automation:
The scenarios are automated using testing frameworks and tools, such as Cucumber.

4. Continuous Feedback:
BDD scenarios provide continuous feedback on the software's behavior throughout its development lifecycle. They help identify discrepancies between the expected and the actual behavior.

Example of a BDD Scenario (using Gherkin syntax):

Suppose you are developing a simple calculator application, and the business requirement is to ensure that the addition works correctly.

Step Definitions (using Java with Cucumber example):

@Given ("^I have entered (\\d +) into the calculator $") 
public void enterNumber(int number) { 
// Code to enter the number into the calculator 
} 

@When("^I press the \" Add\" button $") 
public void pressAddButton() { 
// Code to press the "Add" button 
} 

@Then ("^the result should be (\\d +) on the screen $") 
public void verify Result(int expected) { 
// Code to verify the result displayed on the screen 
}

Here, BDD brings together the business requirements, the development team, and the testing team. The Gherkin scenario specifies the behavior, and the step definitions implement the automation logic. This approach ensures that everyone is on the same page regarding the expected behavior of the software, resulting in better communication and higher software quality.

Which Language is Used in Cucumber?

Cucumber supports various programming languages for writing automation test scripts and step definitions. However, the common language used to write scenarios is Gherkin syntax, which remains the same across different programming languages. The supported programming languages for writing Cucumber test scripts and step definitions include Java, Python, Ruby, JavaScript, and more.

Let's explore how Gherkin syntax is used in Cucumber scenarios with examples in different programming languages:

1. Gherkin Scenario:

2. Java Step Definitions:

import io.cucumber.java.en.Given ; 
import io.cucumber.java.en.When ; 
import io.cucumber.java.en . Then ; 

public class AdditionSteps { 
private int result ; 

@Given ("^I have entered (\\ d +) into the calculator $") 
public void enterNumber(int number ) { 
// Code to enter the number into the calculator 
} 

@When ("^I press the \"Add\" button $") 
public void pressAddButton() { 
// Code to press the "Add" button 
result = Calculator.addNumbers() ; 
} 

@Then ("^the result should be (\\d +) on the screen $") 
public void verifyResult(int expected) { 
// Code to verify the result displayed on the screen 
assert result == expected ; 
}
}

3. Python Step Definitions:

from behave import given , when , then 

@given ('I have entered { number : d ) into the calculator') 
def enter_number(context , number):
# Code to enter the number into the calculator 

@when('I press the "Add" button') 
def press_add_button(context): 
# Code to press the " Add " button 
context.result = Calculator.add_numbers() 

@then('the result should be {expected : d} on the screen') 
def verify_result(context , expected): 
# Code to verify the result displayed on the screen 
assert context.result == expected

4. Ruby Step Definitions:

Given ( 'I have entered { int } into the calculator ' ) do | number | 
# Code to enter the number into the calculator 
end 

When ( 'I press the "Add" button' ) do 
# Code to press the "Add" button 
@result = Calculator.add_numbers() 
end 

Then ( 'the result should be {int} on the screen' ) do | expected | 
# Code to verify the result displayed on the screen 
expect(@result ).to eq(expected) 
end

5. JavaScript Step Definitions (Cucumber.js):

const { Given , When , Then } = require ( ' @ cucumber / cucumber ' ) ; 

Given ( ' I have entered {int} into the calculator ', function ( number ) { 
// Code to enter the number into the calculator 
} ) ; 

When ( 'I press the "Add" button ', function() { 
// Code to press the " Add " button 
this.result = Calculator.addNumbers() ; 
} ) ; 

Then ( 'the result should be {int} on the screen ', function (expected) { 
// Code to verify the result displayed on the screen 
expect (this.result).to.equal(expected) ; 
} ) ;

In each programming language, the step definitions implement the actions and verifications specified in the Gherkin scenarios. The programming language chosen for step definitions depends on your team's familiarity and the programming ecosystem of your project.

Basic Terms of Cucumber

Cucumber uses a specific vocabulary to define and structure its scenarios, making it easier to write and understand test specifications. 

Some of the basic terms used in Cucumber, along with examples to illustrate their usage:
Feature, Scenario and  Step Definitions, are already detailed.

Given, When, Then, And, But:

- These are keywords used to structure scenarios and define steps in Gherkin syntax.
- 'Given' describes the initial context or state
- 'When' represents an action or event that triggers the scenario
- 'Then' specifies the expected outcome or result
- 'And' and 'But' are used to add additional steps and enhance readability

Example:

6. Background:

- The 'Background' keyword is used to define steps that are common to all scenarios within a feature
- It reduces duplication of steps and enhances scenario clarity

Example:

How Does Cucumber Testing Work?

Cucumber testing involves writing human-readable scenarios in Gherkin syntax and mapping them to automated step definitions in your chosen programming language, which executes the actions and verifications described in the scenarios.

Here's how Cucumber testing works with an example:

Step 1: Write Scenarios in Gherkin Syntax:
You start by writing scenarios in Gherkin syntax, describing the expected behavior of the software.

Example:

Step 2: Map Scenarios to Step Definitions:
Each step in the scenario is matched to a corresponding step definition written in your chosen programming language (Java, Python, Ruby, etc.). These step definitions contain the automation logic that performs the actions and verifications specified in the scenario.

Example (Java with Selenium WebDriver):

@Given ("^the user is on the login page $") 
public void userIsOnLoginPage() { 
// Code to navigate to the login page 
} 

@When("^the user enters valid credentials $") 
public void userEntersValidCredentials() { 
// Code to enter valid username and password 
} 
@And ("^clicks the \"Login\" button $") 
public void userClicksLoginButton() { 
// Code to click the login button 
} 
@Then ("^the user should be redirected to the dashboard $") 
public void userRedirected ToDashboard() { 
// Code to verify that the dashboard page is displayed 
}

Step 3: Automation Execution:
When you run the Cucumber test suite, the Cucumber framework reads the scenarios and their step definitions. It then executes the step definitions in the correct order, simulating the user interactions and verifying the expected outcomes.

Step 4: Reporting and Results:
Cucumber generates reports that provide insights into the execution status of each scenario and step. You can identify which steps passed, failed, or were skipped, along with any error messages.

Benefits of Cucumber Testing:

- Collaboration: All team members can understand and contribute to scenarios


- Clarity: Scenarios provide clear documentation of software behavior


- Reusability: Step definitions can be reused across different scenarios


- Maintainability: Changes to scenarios are reflected in the code without changing the automation logic


- Automation: The testing process is automated for quicker and more consistent testing

Software Tools Supported by Cucumber

Here are some software tools and technologies that Cucumber commonly supports:

1. Automation Frameworks:

Cucumber can be integrated with automation frameworks like Selenium, Appium, and Protractor to automate web and mobile application testing.

Example (Cucumber with framework Selenium):

Java Step Definitions:

@Given("^the user is on the Google search page $") 
public void userIsOnGoogle SearchPage() { 
// Code to navigate to Google search page 
} 

@When("^the user enters \ "([^\"]*)\" in the search bar $") 
public void user EntersSearchQuery(String query) { 
// Code to enter search query 
} 

@And("^clicks the \" Search\"button $") 
public void userClicksSearchButton() { 
// Code to click search button 
} 

@Then("^the search results should include \"([^\"]*)\"$") 
public void verifySearchResults(String expectedResult) { 
// Code to verify search results 
}

2. Continuous Integration Tools:

Cucumber can be integrated with CI/CD tools like Jenkins, Travis CI, and CircleCI to automate test execution as part of the development pipeline.

3. Reporting Tools:

Cucumber supports integration with reporting tools like ExtentReports and Allure to generate detailed and visual test reports.

4. Version Control Systems:

Cucumber scenarios and step definitions can be stored in version control systems like Git, allowing teams to collaborate on test scripts.

5. Browser Drivers:

Browser drivers such as ChromeDriver and GeckoDriver can be used with Cucumber to automate browser interactions.

6. API Testing Tools:

Cucumber can be used for testing APIs by integrating with tools like REST Assured and Karate.

7. Mobile Testing Tools:

Cucumber can be used for mobile app testing by integrating with tools like Appium for mobile automation.

8. Database Tools:

Cucumber can be integrated with database testing tools to verify database interactions in scenarios.

9. Mocking and Stubbing Frameworks:

Mocking frameworks like Mockito and Stubborn can be used with Cucumber to isolate components during testing.

10. Performance Testing Tools:

Cucumber can be integrated with performance testing tools like JMeter for end-to-end testing.

11. Containerization Tools:

Cucumber can be used with containerization tools like Docker for testing in isolated environments.

The flexibility of Cucumber's architecture and its support for various programming languages make it adaptable to a wide range of tools and technologies, enabling you to create powerful and comprehensive test automation solutions.

Advantages of Cucumber Tool

Some key advantages of using the Cucumber tool are:

1. Shared Understanding: Cucumber scenarios are written in a natural language format that is easily understood by both technical and non-technical stakeholders. This fosters a shared understanding of software requirements and behaviour.

2. Collaboration: Cucumber promotes collaboration between business analysts, developers, testers, and other team members. Everyone can contribute to defining scenarios and verifying behaviour.

3. Clear Documentation: Scenarios serve as clear and concise documentation of the expected behaviour of the software, making it easier to maintain and understand the test suite.

4. Reusability: Step definitions can be reused across different scenarios, reducing duplication of code and effort.

5. Isolation of Steps: Each step in a scenario is separate from others, allowing for isolation and easier debugging if a step fails.

6. Automation: Cucumber scenarios can be automated using step definitions, providing consistent and repeatable testing.

7. Versatility: Cucumber supports multiple programming languages and frameworks, allowing teams to use their preferred tools and technologies.

8. Early Detection of Issues: BDD scenarios are written before development starts, allowing for early detection of potential issues and misunderstandings.

9. Reduced Ambiguity: Gherkin syntax enforces a clear structure for defining scenarios, reducing ambiguity in requirements.

10. Non-Technical Involvement: Cucumber enables non-technical team members to actively participate in the testing process by writing and reviewing scenarios.

11. Test Reporting: Cucumber generates comprehensive and readable test reports, highlighting which steps passed and which failed.

12. Continuous Integration: Cucumber integrates well with CI/CD pipelines, allowing automated testing to be part of the development workflow.

13. Regression Testing: Automated Cucumber scenarios provide an efficient way to perform regression testing and ensure that new changes don't break existing functionality.

Conclusion

Cucumber stands out as a transformative force in the constantly changing world of software testing, reshaping how teams approach the daunting task of ensuring software quality. Cucumber is a leader in testing innovation because it promotes collaboration, improves readability, and streamlines efficiency. Its seamless integration of multi-language compatibility and user-friendly Gherkin syntax empowers teams to design complex tests that seamlessly align with the complex web of business requirements. The principles of Behavior-Driven Development (BDD) have served as our compass throughout this journey, illuminating the way to accuracy and clarity. 

FAQs

1. What is a Cucumber Framework Example?

A Cucumber framework example involves writing Gherkin scenarios that describe the behaviour of an application and implementing step definitions to automate those scenarios. This enables efficient testing and collaboration among team members.

2. What is the Cucumber Framework?

The Cucumber framework is a testing framework that supports Behavior-Driven Development. It allows teams to write human-readable scenarios in Gherkin syntax and automate them using step definitions, fostering collaboration and efficient testing.

3. How Does Cucumber Python Work?

Cucumber Python follows the same principles as other Cucumber implementations. You write Gherkin scenarios in feature files and implement step definitions in Python. The step definitions execute the desired actions and assertions.

Leave a Reply

Your email address will not be published. Required fields are marked *