How to write Cucumber Script and its Step definition with Java?

We have discussed a lot on Cucumber and now we came at the position where it becomes mandatory to understand the technique to write cucumber script and its step definition. Therefore, our agenda of this tutorial is about developing Cucumber scripts and implementation of its step definition by using Java programming language.

One point you should be clear that you must know steps to create a new feature file. If you know then that’s very good, else, you click on below link to know the steps to create a new cucumber feature file.

How to create first feature file in Cucumber?

You should also know the cucumber file structure, therefore, to know more about cucumber file structure click on below link.

What is the structure of the Cucumber file?

Since we are using Gherkin syntax to design our Cucumber script, hence, I would like to suggest you 5 minutes reading on Gherkin syntax article.

What is Gherkin Syntax for Behaviour Driven Development?

If you have finished reading above suggested articles then I am pretty sure that you are at such level where you can easily write cucumber script, but, you may find hard to write and design an efficient and nice step definition.

Let’s begin with Step definition first.

How to write and design step definition of the Cucumber script?

We use anchors and annotation with respect to Gherkin syntax to design the step definition. Let’s look at them.

Anchors used in the Step definition

We use anchors to start and end the step definition, therefore-

  • ^ is used to begin the step definition
  • And, $ is used to end the step definition

Further, we use annotations like @Given, @And, @When, @Then and @But.

The step definition will look like-

@Given(“^User opens the Website$”)

How to implement Cucumber step definition with Java programming?

Let’s take a simple Cucumber script and further we will see its step definition with Java programming.

MyFeature.feature

#Author: Avinash Mishra

Feature: My First Cucumber Feature
  I want to use this template for my sample test

@tag1
Scenario: Step Definition Implementation
Given I provide first Integer
And I provide second Integer
Then I perform addition of above two numbers
And I print output of addition to console

Above is the cucumber feature file which performs the addition of two numbers and printing their result in the console.

Now coming to the implementation of their step definition by using Java programming. First, create a new package then create a new Java class where you will keep the step definition’s implementation.

StepDefinitionImplementation.class

We see that after each step definition, there comes a method which implements the logic of that step.

package Steps;

import java.util.Scanner;

import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;

public class StepDefinitionImplementation {
	
	 int a, b, c;
	
	@Given("^I provide first Integer$")
	public void getFirstNumber(){
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter your first number");
		
		a = sc.nextInt();
	}
	
	@And("^I provide second Integer$")
	public void getSecondNumber(){
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter your second number");
		
		b = sc.nextInt();
	}
	
	@Then("^I perform addition of above two numbers$")
	public int addition(){
		return c=a+b;
	}
	
	@And("^I print output of addition to console$")
	public void printValue(){
		
		System.out.println("Addition of two numbers is- "+c);
		
	}

}

How to run Cucumber Script in Eclipse?

Now go to your Cucumber feature file and do a right click. Then hover over Run As option then clicks on Cucumber Feature. The program will start running. It does not require the main method.

Run Cucumber Script

Here is the console output.

Console output of Cucumber script step definitionIn the above image, We see that Cucumber sends the detailed log to the console.

This was all about creating step definitions for Cucumber script. Let’s dive deep into the Cucumber now.

How to use Variable and String in Cucumber script and step definition?

In the above step definition, we have seen that user sends the input. Now we will hard code variable and string in test step in Cucumber feature file and step definition as well.

@Given("^I provide one integer as (\\d+)$")
       public void I_provide_one_integer_as(int a)   {     
              System.out.format("I provide one integer as %n", a);
       }

Here \\d is the regular expression to indicate integer. Let’s have a look at some of the regular expressions which is used to make cucumber scripts interactive.

  • d is used for digit
  • + used to show one or more digit
  • \d+ means at least one digit matches with the expected data
  • . (dot) means any character
  • .* (dot star) means at least any character matches

How to use a random and multiple-choice variable in Cucumber script and Step definition?

Sometimes we come across a scenario where the user needs to choose multiple steps however, there is a common method among these multiple steps so we can use the random variable technique to handle this redundancy.

@Given("^User opens (?:Chrome | Mozilla | Opera) browser")
       public void user_opens_x_browser(String browserName) {     
              goToBrowser(browserName);
       }

How to implement data driven testing with Cucumber?

A data driven testing appreciates testing of the functionality by a different set of test data. In short, we can say that it is a kind of data driven framework.

Let’s first create a Cucumber feature file and we will pass data through it using a data table.

DataDriven.feature

#Author: Avinash Mishra

Feature: Data driven framework with Cucumber
  This is data driven framework with cucumber using data table

  @tag1
  Scenario: Step definition for data driven framework
    Given I have the following test data
       |username | password|
       |avinash  | pwd1    |
       |Mishra   |  pwd2   |
       |test     |  test   |

Noe let’s look into its step definition.

DataDrivenStepDefinition.class

package Steps;

import java.util.Map;

import cucumber.api.DataTable;
import cucumber.api.java.en.Given;

public class DataDrivenStepDefinition {
	

	@Given("^I have the following test data$")
	public void I_have_the_following_test_data(DataTable dt)	{	
		for(Map<String, String> map : dt.asMaps(String.class, String.class)){
			String username = map.get("username");
			String password = map.get("password");
		   System.out.println("User Name- "+username+"\n"+"Password- "+password);
		}	
	}
}

Here is the console output.

Data Driven Framework Cucumber script step definition Different hooks in Cucumber Script

Hooks are the block of codes which are executed before and after the scenario. It acts like TestNG annotations. So, cucumber supports only two hooks which are-

  • @Before- It is used as preconditions like opening a browser, setting up the environment, etc.
  • @After- It is used after the completion of the test like closing browser, generating reports, etc

Some of the points related to Hooks are as follows-

  • @After hooks will be executed even the test fails
  • You must import the packages- api.java.After and cucumber.api.java.Before
  • We can give priority to the hooks by using Order=n, where n = 0,1,2,3..
  • Priority for @Before hooks will be in ascending order, whereas, priority for @After hooks will be in descending order

This was all about designing a cucumber script and its step definition. Post your queries in a comment below and don’t miss to join our Facebook group for quick updates. Click here to know more about Step Definitions.

Join Inviul fb group

2 Comments

Leave a Reply