Show List
Test Rest API Using Serenity Cucumber and Gradle
In this example, we will demo testing a REST API with Serenity Cucumber and Gradle. We will be using the rest API from the previous chapter
Serenity is Open Source BDD test framework. It provides wrapped APIs with other test libraries such as serenity-cucumber, serenity-rest-assured, serenity-junit, serenity-screenplay, serenity-reports etc. It also provides powerful reporting and living documentation features.
Here is the project structure. Files under src/main/java are to create the REST API as discussed in the previous chapter. You can download the source code from there to code along. We are only going to add the files under test folder and update build.gradle to test the API.
Here is a quick view of different endpoints the developed REST API supports. For this demo we are only going to write the scripts to test the GET operation on /student/{id} end point.
Add Gradle Dependencies
Add below dependencies in build.gradle file. See the build.gradle full code below for reference.
testImplementation 'net.serenity-bdd:serenity-cucumber6:2.6.0'
testImplementation 'net.serenity-bdd:serenity-screenplay:2.6.0'
testImplementation 'net.serenity-bdd:serenity-screenplay-rest:2.6.0'
testImplementation 'net.serenity-bdd:serenity-rest-assured:2.6.0'
testImplementation 'junit:junit:4.13.1'
testImplementation 'io.rest-assured:rest-assured:4.3.3'
Feature File
Here is the feature file for the project. Feature file documents the steps for the test.
In this test scenario, we will be sending a valid test request to get the student details. When the response is received, the values will be validated. Example section is used to dynamically supply the values to the Given/When/Then steps.
APITest.feature
Feature: Validation of get method
@GetStudentDetails
Scenario Outline: Send a valid Request to get student details
Given I send a request to the URL to get student details
Then the response will return status "<rt_status>" and id <id> and name "<st_name>" and grade "<st_grade>"
Examples:
|id |st_name |st_grade |rt_status|
|1 |Ana |One |200|
Step Definition
The code behind each of Given, When and Then step is provided in the step definition file. We are using REST assured to make the call and then to validate the response.
API_StepDefinitions.java
package com.example.demo.stepdefinitions;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
public class API_StepDefinitions {
private ValidatableResponse apiResponse;
private String endpoint = "http://localhost:8080/student/1";
@Given("I send a request to the URL to get student details")
public void sendRequest(){
apiResponse = given().contentType(ContentType.JSON)
.when().get(endpoint).then();
System.out.println("Response :"+apiResponse.extract().asPrettyString());
}
@Then("the response will return status {string} and id {int} and name {string} and grade {string}")
public void verify(String statusCode, Integer st_id, String st_name, String st_grade) {
apiResponse.assertThat().statusCode(Integer.parseInt(statusCode));
apiResponse.assertThat().body("student_id",equalTo(st_id));
apiResponse.assertThat().body("name",equalTo(st_name));
apiResponse.assertThat().body("grade",equalTo(st_grade));
}
}
Test Runner
In the test runner we are using the CucumberWithSerenity class to run the test. CucumberOptions annotation is used to bind the feature and step definition.
package com.example.demo.runner;
import org.junit.runner.RunWith;
import io.cucumber.junit.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;
@RunWith(CucumberWithSerenity.class)
@CucumberOptions(plugin ="pretty",features= {"src/test/resources/features/APITest.feature"}, glue= {"com.example.demo.stepdefinitions"})
public class TestRunner {
}
Build.gradle
Here is the build.gradle for the project.
Plugin serenity-bdd.serenity-gradle-plugin provides additional tasks to be executed through gradle such as creating reports. Aggregate is one such task that has been added to be executed when test task is completed.
plugins {
id 'java'
id "net.serenity-bdd.serenity-gradle-plugin" version "3.5.0"
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.7.3'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.4'
implementation 'org.springframework.boot:spring-boot-starter-web:2.7.0'
runtimeOnly 'com.h2database:h2:2.1.214'
testImplementation 'org.springframework.boot:spring-boot-starter-test:2.7.0'
testImplementation 'net.serenity-bdd:serenity-cucumber6:2.6.0'
testImplementation 'net.serenity-bdd:serenity-screenplay:2.6.0'
testImplementation 'net.serenity-bdd:serenity-screenplay-rest:2.6.0'
testImplementation 'net.serenity-bdd:serenity-rest-assured:2.6.0'
testImplementation 'junit:junit:4.13.1'
testImplementation 'io.rest-assured:rest-assured:4.3.3'
}
test {
testLogging.showStandardStreams = true
systemProperties System.getProperties()
}
test.finalizedBy(aggregate)
serenity {
reports = ["single-page-html"]
}
gradle.startParameter.continueOnFailure = true
Running the tests
Start the Spring Boot application to launch the API and then run the tests. Tests can be executed through IDE or by running the "gradle test" command from project home. Here is a trimmed down log:
PS C:\Users\mail2\Downloads\Rest-Service-Testing-with-Serenity-Cucumber> gradle test > Task :test Send a valid Request to get student details(validation-of-get-method;send-a-valid-request-to-get-student-details) -------------------------------------------------------------------------------- 15:05:36.502 [Test worker] INFO net.thucydides.core.model.TestOutcome - SetUserStory Validation of get method 15:05:36.509 [Test worker] INFO net.thucydides.core.model.TestOutcome - SetUserStory Validation of get method 15:05:36.574 [Test worker] DEBUG net.thucydides.core.requirements.model.cucumber.CucumberParser - Added feature Validation of get method org.apache.http.impl.conn.BasicClientConnectionManager - Connection can be kept alive for 60000 MILLISECONDS Response :{ "student_id": 1, "name": "Ana", "grade": "One" } Given I send a request to the URL to get student details # com.example.demo.stepdefinitions.API_StepDefinitions.sendRequest() Then the response will return status "200" and id 1 and name "Ana" and grade "One" # com.example.demo.stepdefinitions.API_StepDefinitions.verify(java.lang.String,java.lang.Intege r,java.lang.String,java.lang.String) 15:05:39.219 [Test worker] INFO - _____ ___ ___ _____ ___ _ ___ ___ ___ ___ |_ _| | __| / __| |_ _| | _ \ /_\ / __| / __| | __| | \ | | | _| \__ \ | | | _/ / _ \ \__ \ \__ \ | _| | |) | |_| |___| |___/ |_| |_| /_/ \_\ |___/ |___/ |___| |___/ Send a valid Request to get student details ---------------------------------------------------------------------- com.example.demo.runner.TestRunner STANDARD_OUT 1 Scenarios (1 passed) 2 Steps (2 passed) 0m3.220s 15:05:39.233 [Test worker] DEBUG net.thucydides.core.reports.ReportService - Reporting formats: [JSON, HTML] 15:05:39.324 [Test worker] DEBUG net.thucydides.core.reports.ReportService - Reporting formats: [JSON, HTML] 15:05:39.339 [Test worker] DEBUG net.thucydides.core.reports.ReportService - Generating reports for 1 test outcomes using: net.thucydides.core.reports.json.JSONTestOutcomeReporter@ 16c1519e 15:05:39.340 [pool-1-thread-1] DEBUG net.thucydides.core.reports.ReportService - Processing test outcome Validation of get method:Send a valid Request to get student details 15:05:39.340 [pool-1-thread-1] INFO net.thucydides.core.reports.ReportService - net.thucydides.core.reports.json.JSONTestOutcomeReporter@16c1519e: Generating report for test outcom e: Validation of get method:Send a valid Request to get student details 15:05:39.349 [pool-1-thread-1] DEBUG net.thucydides.core.reports.json.JSONTestOutcomeReporter - Generating JSON report for Send a valid Request to get student details to file C:\Us ers\mail2\Downloads\Rest-Service-Testing-with-Serenity-Cucumber\target\site\serenity\51f8cc5193fa2cf2cff626822ecc96a7060884e3320588ac7edff826410b514c.json (using temp file C:\Users\mai l2\Downloads\Rest-Service-Testing-with-Serenity-Cucumber\target\site\serenity\51f8cc5193fa2cf2cff626822ecc96a7060884e3320588ac7edff826410b514c.jsonb8cac9ba-f731-403d-9b4f-5e92e96875de) 15:05:40.213 [Test worker] INFO io.cucumber.core.plugin.SerenityReporter - Cleanup test resources for URI file:///C:/Users/mail2/Downloads/Rest-Service-Testing-with-Serenity-Cucumb er/src/test/resources/features/APITest.feature > Task :aggregate Generating Serenity Reports - Main report: file:///C:/Users/mail2/Downloads/Rest-Service-Testing-with-Serenity-Cucumber/target/site/serenity/index.html - Test Root: null - Requirements base directory: null BUILD SUCCESSFUL in 11s
Serenity Report
Link to the Serenity report is printed in the log above. Serenity provides rich and detailed test report:
Source Code:
https://github.com/it-code-lab/Rest-Service-Testing-with-Serenity-Cucumber
Leave a Comment