Skip to main content

Cucumber setup using Gradle

This tutorial will help you configure Cucumber into a Java project using the Gradle build tool.

Introduction

Cucumber is a test automation tool that supports Behavior-Driven Development (BDD). It is written in plain English text called "Gherkin." Cucumber enables you to write test cases that anyone can easily understand, regardless of their technical knowledge.

Setup

First, create a Gradle project using the gradle init command.

> gradle init

Complete the Gradle wizard to create a project.


Now update the gradle.build file to add the Gradle Cucumber dependency.

testImplementation 'io.cucumber:cucumber-java8:7.0.0'

This will add Cucumber implementation to your project.


Task Configuration

Add the following configuration to gradle.build
This will enable the Cucumber runtime to execute BDD test cases.

configurations {
    cucumberRuntime {
        extendsFrom testImplementation
    }
}


Create a new custom task to execute Cucumber 

task cucumber() {
    dependsOn assemble, testClasses
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = [
                    '--plugin', 'pretty',
                    '--plugin', 'html:target/cucumber-report.html',
                    '--glue', 'com.zainabed.cucumber.bdd',
                    'src/test/resources']
        }
    }
}

NOTE: com.zainabed.cucumber.bdd is reference to a package name, You should put in your project package name..

Cucumber Options/Args

glue:    Project package name where you define the glue code.
plugin:    Plugins which you want to add in the project.
pretty:    Generate a pretty report
html:    Generate Cucumber HTML report.
src/test/resources:     Location of feature files.

Feature File

Cucumber interprets the Gherkins feature file and executes the glue code associated with it.

Therefore, create a features folder inside the test resources section src/test/resources/ and add the Gherkin feature which gets executed by cucumber.

Feature: User Registration
  User will initiate registration request to system and
  system will validate the information and add user to system

  Scenario: Basic Flow
    Given User visit registration
    When User enter his registration details
    Then System validate the information
    And User get registered


Run the Task

Next, run the following command to execute Cucumber test cases.

./gradlew cucumber

It will fail and give you the glue code that you need to add to your project like this.

> Task :app:cucumber FAILED

Scenario: Basic Flow                       # src/test/resources/features/user-registration.feature:5
  Given User visit registration
  When User enter his registration details
  Then System validate the information
  And User get registered

Undefined scenarios:
You can implement missing steps with the snippets below:

Given("User visit registration", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java8.PendingException();
});
When("User enter his registration details", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java8.PendingException();
});
Then("System validate the information", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java8.PendingException();
});
Then("User get registered", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java8.PendingException();
});


Glue Code

In order to fix the cucumber task error, we need to provide glue code, which is nothing but a Java class.

Create a new Java file named UserRegistrationBDD.java inside bdd package and add the above code into it.
package com.zainabed.cucumber.bdd;

import io.cucumber.java8.En;

public class UserRegistrationBDD implements En {

    public UserRegistrationBDD() {

        Given("User visit registration", () -> {
            // Write code here that turns the phrase above into concrete actions
            throw new io.cucumber.java8.PendingException();
        });

        When("User enter his registration details", () -> {
            // Write code here that turns the phrase above into concrete actions
            throw new io.cucumber.java8.PendingException();
        });

        Then("System validate the information", () -> {
            // Write code here that turns the phrase above into concrete actions
            throw new io.cucumber.java8.PendingException();
        });

        Then("User get registered", () -> {
            // Write code here that turns the phrase above into concrete actions
            throw new io.cucumber.java8.PendingException();
        });
    }

}

Add some business logic to it, then rerun it.

Note: Cucumber Java 8 dependency uses constructor and English "En" interface to implement glue code.

Add your business logic and assertions to execute features. 


Re-Run the Cucumber Task

At the end, execute the cucumber tasks.


> Task :app:cucumber
Scenario: Basic Flow                       # src/test/resources/features/user-registration.feature:5
  Given User visit registration            # com.zainabed.cucumber.bdd.UserRegistrationBDD.<init>(UserRegistrationBDD.java:9)
  When User enter his registration details # com.zainabed.cucumber.bdd.UserRegistrationBDD.<init>(UserRegistrationBDD.java:13)
  Then System validate the information     # com.zainabed.cucumber.bdd.UserRegistrationBDD.<init>(UserRegistrationBDD.java:17)
  And User get registered                  # com.zainabed.cucumber.bdd.UserRegistrationBDD.<init>(UserRegistrationBDD.java:21)
1 Scenarios (1 passed)
4 Steps (4 passed)


Conclusion 

This tutorial demonstrated the setup and configuration of the Cucumber test framework using the Gradle build tool.

Full source can be found on the Github page.

Comments

Subscribe for latest tutorial updates

* indicates required

Popular posts from this blog

How to enable SQL logs in Spring Boot application?

This tutorial will demonstrate how to enable and disable SQL log statements in a Spring Boot application in order to debug SQL flow. Problem You will frequently need to debug the SQL statement while developing a Spring Boot application with a SQL database. SQL debug logs can assist you figure out what's wrong with JPA statements and whether or not there's a problem with database connectivity. Example  If you've built custom Spring data JPA methods and need to know what SQL statement is being utilized behind them, return repository . findByUsernameIn ( usernames ); Then you can enable Hibernet debug mode to log SQL statements. Solution Update the application.yml file with the Hibernet configuration as logging: level: org: hibernate: DEBUG or application.properties as logging.level.org.hibernate=DEBUG The SQL statement will appear in the application logs after modifying the configuration file and restarting the application. 2022-04-07 08:41...

Preload Images Using Javascript

Preload Image is technique which helps browser to render images with minimum delay. Today we will see example of image gallery. Gallery contain 5 images which load images one after another whenever user clicks next and back button. This is a basic image gallery scenario which is used in all possible website, then why we need preloaded images for this gallery? Now a day’s most of website becoming faster and user expectation is increasing. Suppose your website doesn’t use preload image technique for gallery and a user visits any image gallery from Google Plus or Facebook and visits your website gallery. Then that user always prefer those websites rather than yours. Why? Because your website load one image at a time. When user click on next button, then only gallery load image and user has wait till it get loaded. To avoid this situation gallery needs to download all images ...

JSON Tutorials : Getting Started

JSON is widely accepted text formatted structured data. JSON stands for " JavaScript Object Notation ". In general JSON can represent 1. Object of database record. 2. Object to represent a list of HTML elements. 3. Result of search query. 4. Response of an Ajax call. Here you can see JSON is used in many different areas and for many different scenarios. This means it has simple data structure. most of programming languages adopt it and it can flow easily from one connection to another. You can find JSON office definition here JSON Official Site . JSON is represented by two structural types, which includes two primitive types. Structural types Array : A sequential list of primitive data types between square brackets [ ] Object : Collection of key, value pair stored inside curly braces { }, where value would be primitive data type Primitive types : There are two primitive types key and value. " key " should be string and " value (data type)...