BDD With Java


BDD (Behaviour driven development) adapted features of TDD(Test Driven development) and extended a few syntax, which made the Product Owner (PO Role of Scrum Process) or Business Analyst job easy to convert requirements into standard scripts, by analysing the behaviour of features required by customers. And the developer's job will be easy with this behaviour, scripts drive the development.


  • A Developer should know Java
  • Recommend reading about TDD first.

We will see this BDD with an example of calci. BDD is following Gherkin syntax's. An example will be illustrated below Gherkin syntax's

  • Feature:
  • Scenario:
  • Given
  • When
  • Then

Requirement from the customer: Build a calculator app, for 2 numbers addition and subtraction

For BDD, we will use "io.cucumber" package, which is available in java. Install the package by putting below statement in build.gradle file

implementation group: 'io.cucumber', name: 'cucumber-java', version: '7.2.3'

Convert requirements into feature file like below using Gherkin syntax,

File name: calci.feature

Feature: Test Calci
  Scenario: Add 2 numbers
    Given Calci app is running
    When Provided input 2 and 2 with add
    Then get result 4

  Scenario: Substract 2 numbers
    Given Calci app is running
    When Provided input 5 and 2 with sub
    Then get result 3

For Gherkin syntax keywords, write steps like below

File name:


import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalciStepdef {

    int result = 0;
    Calci calci=null;

    @Given("Calci app is running")
    public void step_impl(){
        System.out.println("Calci app is running");
        calci = new Calci();

    @When("Provided input {int} and {int} with add")
    public void step_impl_A(int a, int b){
        result = calci.Add(a, b);

    @When("Provided input {int} and {int} with sub")
    public void step_impl_B(int a, int b){
        result = calci.Sub(a, b);

    @Then("get result {int}")
    public void step_impl_c(int out){
        assertEquals(result, out);

Below is the file which actually contains business logic. Actually, here to develop this, we need to follow TDD. As the article is to know about BDD. I am putting code directly.

public class Calci {
    public int Add(int a, int b) {
        return a + b;
    public int Sub(int a, int b) {
        if (a > b) {
            return a - b;
        return b - a;

Normally, a file/folder structure should look like the one below.

BDD with Java

Now execute the feature file, Below is the output window,

BDD with Java


In this article, we understood BDD and its use from converting use case to code.