Cucumber is a Behavior-Driven Development (BDD) tool , which allows the developers and testers to write different tests in a human-readable form that directly bridges the gap between technical and non-technical stakeholders. Cucumber allows the teams to guarantee expected behavior in their software & satisfy business needs with same, development time efficiency.
In this article ,we will go through the steps required to setup Cucumber in Java project, starting from installation of tools to setting up the project and then verify the set-up as well.
Installation of Java & Maven/Gradle
Before going in-depth with setting up the project, it's very essential to ensure the foundational components, like Java & Maven/Gradle installation.
Installing Java
Cucumber works well with Java , so first thing you must do is download JDK (Java Development Kit) properly and set up in your system. Here are some steps to do it
- Download JDK: Download JDK from Oracle Website . You may also choose the open-source version like OpenJDK as well.
- Install JDK: Install the JDK by following steps according to your Operating System & then set up the Environment Variable ( for Windows ) or PATH ( for Linux/macOS ).
- Verify the Installation of JDK: Open the terminal or command prompt and run the following command .
Java version- If Java is installed correctly , this command will give the version of the installed JDK.
Installing Maven or Gradle
Maven & Gradle are the build tools that are used to manages the dependencies and the project structure and provide easy-ness to work with Java Projects.
- Install Maven: Download Maven from Apache Maven website . After downloading , follow the instructions for your Operating System to set up Maven , Also you can check for the version as follows :
Maven Version- Install Gradle: Similarly , Gradle can be downloaded from the official website . Follow the installation process for your platform & check the version as follows :
Gradle VersionAfter installing Java & build tools , you are ready to create Cucumber project. so without further a do we are going to start setting up cucumber project.
Setting Up a Cucumber Project
Now Java & Maven / Gradle are installed in our System , let's set up the cucumber project :
Maven Set Up
- Open your preferred IDE such as IntelliJ IDEA , Eclipse or NetBeans. And create a new Maven Project.
- Please Specify the " artifactId " and " groupId " for the project. Usually they are like as " com.example.cucumber " and " CucumberTestingProject ".
- Now , select the appropriate JDK Version for the project and make sure it must be compatible with latest cucumber version.
Maven Setup in Cucumber Testing ProjectGradle Set Up
- If in-case you use Gradle , then Open the IDE and create new Gradle project.
- Similar to Maven , specify the project group & name fields for your project.
- Also specify the source compatibility , to match the current version of JDK & project version.
Project Structure
Once the project is created , the project structure looks like :
- src/main/java: Contains Application Code
- src/test/java: Contains test code , here all cucumber tests will present.
- src/test/resources: Contains all the features files
Project StructureAdding Cucumber Dependencies
Cucumber requires some specific dependencies to work with a Java project and depending on whether you're using Maven or Gradle , you need to add these specific dependencies to your project file.
In case Maven is Used
If user use the Maven , then all these dependencies are need to be added into the " pom.xml " file under the " <dependencies> " section.
pom.xml with dependencies
Pom.xml dependencies
XML
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>7.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
In case Gradle is Used
If in-case the user uses the Gradle as build tool , then add the following dependencies under the " dependencies " section of " build.gradle " file.
XML
dependencies {
testImplementation 'io.cucumber:cucumber-java:7.0.0'
testImplementation 'io.cucumber:cucumber-junit:7.0.0'
}
After adding all these dependencies , please refresh project or to synchronize your project to download all these required library to your local system from the remote server.
Configuring Cucumber Project
Once the basic configuration is completed , we have to configure cucumber , so that it is aware of your all the test cases and features file. The configuration of cucumber is easy , it is typically done by creating the " Runner class " that internally uses the JUnit to run all the Cucumber tests.
How to Create Runner Class
For creating Runner class Navigate " src/test/java " directory & create a new class called as " TestRunner.Java " .
TestRunner.java
Java
// here is the code implementation of Runner Class
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(
features = "src/test/resources/features", //Path to your feature files
glue ="stepdefinitions" , // Package containg step definitions
plugin = {"pretty","html:target/cucumber-reports.html"}, //Report Generation
monochrome = true // Makes Output Readable
)
public class TestRunner {
// Test Runner Implementations
}
Anatomy of TestRunner Class :
- features : specify the location of the feature files
- glue : points to the package where the step definition is present
- plugin : generate the report in html format.
- monochrome : makes Output readable.
Verifying the Setup
Now it's time to verifying the Cucumber setup whether it is working or Not .
Create a Feature file
In the " src/test/resources/features " directory , create the file " example.feature " and add the following basic scenario :
Java
// example.feature file contains
Feature: Example Feature
Scenario: Basic Cucumber Test
Given this is a basic test Scenario.
Create Step Definitions
Now , navigate to " src/test/java/stepdefinitions " package , and create a class called " StepDefinitions.java " . This is the file that contains the actual code of Gherkins steps .
StepDefinitions.java
Java
// StepDefinitions file coontains
package stepdefinitions;
import io.cucumber.java.en.Given;
public class StepDefinitions {
@Given("this is basic test case scenario")
public void basicTest() {
System.out.println("Cucumber setup is successful!");
}
}
Run the Test Case
Now , finally you can the " TestRunner " class as a JUnit test and if the configuration is correct , you will see the message in the Console , which confirms that the test scenario was executed Successfull.
Case to Demonstrate : Setting Up Cucumber with Java
Let's we will get the step up of cucumber by means of a basic login feature encouraging cucumber test. In this specific case , we will cover a how to form features , stepdefinitions and how to run the test to see the output of specific test case.
Step 1 : Create the Feature file
In Cucumber, all the test cases are to be written in the Feature file using Gherkin Syntax. These files are normal text file , formed under " src/test/resources/features/login.feature " with following content as described in picture.
login.featureStep 2 : Create Step Definitions
Step definitions basically facilitating to provide link the steps from feature file to corresponding Java Code. So to achieve this Create the Java Class named " LoginSteps.java " under Package "stepdefinitions " in the path " src/test/java/stepdefinitions/ " or see in the picture below.
LoginSteps.javaStep 3 : Configure Test Runner File
Now we have to configure test runner class file that will basically tell Cucumber , how to run the test cases. So create class named " TestRunner.java " at the location " src/test/java/ " specified in the below attached picture.
TestRunner.javaStep 4 : Run the Test Case
Basically to Run the Cucumber tests , right-click the " TestRunner.java " file and choose " Run as JUnit Test " Or In IDEs it will automatically suggest in case of IntelliJ adjacent to the class name.
Otherwise use terminnal or command line , navigate to the root directory of project and use Maven or Gradle following Commands :
- For Maven : mvn test
- For Gradle : gradle test
After Running Test Case , Report will generate in HTML FormStep 5 : Expected Output in Console
Here's what you see as output in the console after the test cases are successfully executed :
Output of Cucumber test cases
Step 6 : Generate the HTML Report
Cucumber facilitate to generate the reports in many form like HTML , JSON etc . After running the test Case , a particular HTML report will be generated at location " target/cucumber-reports.html ". we can open this report in your web browser as well , to view detailed report of test execution . As shown Below .
cucumber-report .html (Open in any Web browser)Conclusion
Cucumber provides an easy and efficient way to write all test cases in more readable and maintainable format , it is very useful for the collaboration where non-developers can understand the test logic. By following the above mentioned steps , you will have a Cucumber setup with Java and be able to start writing your own customized BDD Scenarios.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read