Testing of SpringBoot REST Application using Serenity BDD and Rest Assured for GET Method

 HOME

In the previous tutorial, I have explain about SpringBoot and how to perform Integration testing of SpringBoot Application in BDD format using Serenity BDD and Cucumber. In this tutorial, I will explain about the Integration testing of SpringBoot Application for GET method.

Spring Boot is an open-source micro framework which provides Java developers with a platform to get started with an auto configurable production-grade Spring application. 

In this tutorial, lets see a SpringBoot  REST Application and how it can be tested with the help of Rest Assured and Serenity

Below is the structure of a SpringBoot  application project

Below are various Java classes present in a SpringBoot REST Application/API

  • SpringBootRestServiceApplication.java – The Spring Boot Application class generated with Spring Initializer. This class acts as the launching point for application.
  • pom.xml – Contains all the dependencies needed to build this project. 
  • Student.java – This is JPA Entity for Student class
  • StudentRepository.java – This is JPA Repository for Student. This is created using Spring Data JpaRepository.
  • StudentController.java – Spring Rest Controller exposing all services on the student resource.
  • CustomizedExceptionHandler.java – This implements global exception handling and customize the responses based on the exception type.
  • ErrorDetails.java – Response Bean to use when exceptions are thrown from API.
  • StudentNotFoundException.java – Exception thrown from resources when student is not found.
  • data.sql –  Data is loaded from data.sql into Student table. Spring Boot would execute this script after the tables are created from the entities.

HTTP also defines standard response codes.

  • 200 – SUCESS
  • 404 – RESOURCE NOT FOUND
  • 400 – BAD REQUEST
  • 201 – CREATED
  • 401 – UNAUTHORIZED
  • 415 – UNSUPPORTED TYPE – Representation not supported for the resource
  • 500 – SERVER ERROR 

Let’s consider a few HTTP Methods:

  • GET : Should not update anything. Should return same result in multiple calls.

Possible Return Codes 200 (OK) + 404 (NOT FOUND) +400 (BAD REQUEST) 

  • POST : Should create a new resource. Ideally return JSON with link to newly created resource. Same return codes as get possible. In addition – Return code 201 (CREATED) can be used.
  • PUT : Update a known resource. ex: update client details. Possible Return Codes : 200(OK) + 404 (NOT FOUND) +400 (BAD REQUEST) 
  • DELETE : Used to delete a resource. Possible Return Codes : 200(OK).

We will create a Student Resource exposing three services using proper URIs and HTTP methods:

  • Retrieve all Students – @GetMapping(“/students”)
  • Get details of specific student – @GetMapping(“/students/{id}”)
  • Delete a student – @DeleteMapping(“/students/{id}”)
  • Create a new student – @PostMapping(“/students”)
  • Update student details – @PutMapping(“/students/{id}”)

To Test a SpringBoot Application for GET Method, we are using Rest Assured with Serenity BDD. Below mentioned dependencies are added in POM.xml

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-test</artifactId>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>net.serenity-bdd</groupId>
   <artifactId>serenity-core</artifactId>
   <version>2.2.0version>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>net.serenity-bdd</groupId>
   <artifactId>serenity-spring</artifactId>
   <version>2.2.0</version>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>net.serenity-bdd</groupId>
   <artifactId>serenity-cucumber5</artifactId>
   <version>2.2.0</version>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>net.serenity-bdd</groupId>
   <artifactId>serenity-rest-assured</artifactId>
   <version>2.2.0</version>
</dependency>
     
<dependency>
   <groupId>net.serenity-bdd</groupId>
  <artifactId>serenity-screenplay-rest</artifactId>
   <version>2.2.0</version>
   <scope>test</scope>
</dependency>

First, let us see what are @RestController, @AutoWired, @GetMapping and @PathVariable annotations.

1. @RestController

SpringBoot RestController annotation is use to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the request defined handles method.

2. @Autowired

The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans. This is called Spring bean autowiring. To know more about Autowired, you can refer this tutorial.

3. @GetMapping

It is annotation for mapping HTTP GET requests onto specific handler methods.
Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)

4. @PathVariable

This annotation can be used to handle template variables in the request URI mapping, and use them as method parameters.
In this example, we use @PathVariable annotation to extract the templated part of the URI represented by the variable {id}.

A simple GET request to /students/{id} will invoke retrieveStudent with the extracted id value

http://localhost:8080/students/1001

Code of StudentController.java is below

@RestController
public class StudentController {

     @Autowired
     private StudentRepository studentRepository;

     @GetMapping("/students")
     public List retrieveAllStudents() {
           return studentRepository.findAll();
     }

     @GetMapping("/students/{id}")
     public EntityModel retrieveStudent(@PathVariable long id) {
           Optional student = studentRepository.findById(id);
           if (!student.isPresent())
                throw new StudentNotFoundException("id-" + id);
           EntityModel resource = EntityModel.of(student.get());

           WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllStudents());
           resource.add(linkTo.withRel("all-students"));
           return resource;
     }

Scenario 1- Below picture shows how we can execute a Get Request Method on a Resource using Postman

Above scenario can be tested in the below way.

@ReceiveUserDetails
 Scenario Outline: Send a valid Request to get user details
  Given I send a request to the URL "/students" to get user details
  Then the response will return status 200 and id and names and passport_no 
    
Examples:
    |studentID    |studentNames  |studentPassportNo|
    |10010        |Tom           |A1234567         |
    |10020        |Shawn         |B1234568         |
    |10030        |John          |C1239875         |

Test Code to test above scenario (StepDefinition file)

@SpringBootTest(classes = com.springboot.rest.demo.SpringBootRestServiceApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)

public class GetStudentsDefinition {
 
     private final static String BASE_URI = "http://localhost";
     
     @LocalServerPort
     private int port;
     
     private ValidatableResponse validatableResponse;
 
     private void configureRestAssured() {
           RestAssured.baseURI = BASE_URI;
           RestAssured.port = port;
     }
 
     protected RequestSpecification getAnonymousRequest() throws NoSuchAlgorithmException {
           configureRestAssured();
           return given();
     }
 
     @Given("^I send a request to the URL \"([^\"]*)\" to get user details$")
     public void iSendARequest(String endpoint) throws Throwable {
           validatableResponse = getAnonymousRequest().contentType(ContentType.JSON)
    .when().get(endpoint).then();       
     }
 
     @Then("^the response will return status (\\d+) and id (.*) and names (.*) and passport_no (.*)$")
     public void extractResponse(int status, String id, String studentName, 
     String passportNo) {
     validatableResponse.assertThat().statusCode(equalTo(status)).body(containsString(id))
                     .body(containsString(studentName)).body(containsString(passportNo));
 
     }

1. The @SpringBootTest annotation tells Spring Boot to look for a main configuration class (one with @SpringBootApplication, for instance) and use that to start a Spring application context.

2. WebEnvironment.RANDOM_PORT is used to create run the application at some random server port.

3. For assertion purpose, we use Hamcrest Matchers. Hamcrest is a framework for software tests. Hamcrest allows checking for conditions in your code via existing matchers classes. It also allows you to define your custom matcher implementations.

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

4. @LocalServerPort gets the reference of port where the server has started. It helps in building the actual request URIs to mimic real client interactions.

5. ContentType.JSON is imported fromrestassured as well as ValidatableResponse

Scenario 2- Below picture shows how we can execute a Get Request Method to get detail of a specific Student. Here, we want details of student of Id 10020

@ReceiveAUserDetail
   Scenario: Send a valid Request to get user details
    Given I send a request to the URL "/students/10020" to get user detail of a specific user
    Then the response will return status 200 and name "Shawn"

Test Code to test above scenario (StepDefinition file)

@Given("^I send a request to the URL \"([^\"]*)\" to get user detail of a specific user$")
     public void sendRequestForSpecificUser(String endpoint) throws Throwable {
           validatableResponse = getAnonymousRequest().contentType(ContentType.JSON).when().get(endpoint).then();
           System.out.println("RESPONSE :" + validatableResponse.extract().asString());
     }
 
     @Then("^the response will return status (\\d+) and name \"([^\"]*)\"$")
     public void extractResponseOfSpecificUser(int status, String name) {
          validatableResponse.assertThat().statusCode(equalTo(status)).body("name", equalTo(name));
     }

Scenario 3- Below picture shows how we can execute a Get Request Method for incorrect Student

@IncorrectUserId
   Scenario: Send a valid Request to get user details
    Given I send a request to the URL "/students/7" to get user detail of a specific user
    Then the response will return status 404 and message "id-7"

Test Code to test above scenario (StepDefinition file)

@Given("^I send a request to the URL \"([^\"]*)\" to get user detail of a specific user$")
     public void sendRequestForSpecificUser(String endpoint) throws Throwable {
           validatableResponse = getAnonymousRequest().contentType(ContentType.JSON).when().get(endpoint).then();
           System.out.println("RESPONSE :" + validatableResponse.extract().asString()); 
     }
 
     @Then("^the response will return status (\\d+) and message \"([^\"]*)\"$")
     public void extractResponseOfInvalidUser(int status, String message) {
         validatableResponse.assertThat().statusCode(equalTo(status)).body("message", equalTo(message));
 
     }

The next tutorial explains about the Testing of POST method in SpringBoot Application.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s