This sample demonstrates how to write cucumber test cases to test spring boot application using BDD style.
Choose the branch before proceeding to further sections.
Branch | Spring Boot Version | Cucumber Version |
---|---|---|
master | 2.3.9.RELEASE | 6.10.2 |
2.3.9 | 2.3.9.RELEASE | 6.10.2 |
2.1.3 | 2.1.3.RELEASE | 4.2.5 |
1.0.0 | 2.0.3.RELEASE | 1.2.5 |
1.5.6 | 1.5.6.RELEASE | 1.2.5 |
step 1 : To start with cucumber :
Add the below dependencies to support Spring with Cucumber:
<properties>
<cucumber.version>6.10.2</cucumber.version>
</properties>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java8</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-spring</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependencies>
step 2: Define the Cucumber Runner Test
@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/features")
public class CucumberRunnerTest {
}
step 3 : Create a feature file and define the BDD steps using gherkin language
Example : Feature describing the scenario of creating a customer with customer details
Feature: To save the customer with customer details
Scenario: client makes call to POST /customers to save the customer
Given the customer with customer name "barath" and customer id 7777
When the client calls "/customer" with the given details
Then the client receives status code of 200
And the response contains customer name "barath"
step 4 : When you run this feature file Run as -> Cucumber
it generates the BDD style of java code.
Using which you can write the service logic.
@Given("^the customer with customer name \"([^\"]*)\" and customer id (\\d+)$")
public void the_customer_with_customer_name_and_customer_id(String customerName, int customerId) throws Throwable {
}
@When("^the client calls \"([^\"]*)\" with the given details$")
public void the_client_calls_customer_save_with_the_given_details(String path) throws Throwable {
}
@Then("^the client receives status code of (\\d+)$")
public void the_client_receives_status_code_of(int statusCode) throws Throwable {
}
@Then("^the response contains customer name \"([^\"]*)\"$")
public void the_response_contains_customer_name(String customerName) throws Throwable {
}
step 5 : Run the tests and check the output under output folder
mvn test