Spring Boot Rest Assured Example (2024) | TechGeekNext

Spring Boot Rest Assured Example (2024)

In this tutorial, we will learn how to implement and test Rest Assured + TestNG with Spring Boot application.

Q: What is REST Assured?
Ans:

REST Assured is a Java library RESTful APIs testing. It is extensively used to test web applications that are based on JSON and XML. Also, all methods are completely supported, including GET, PUT, POST, PATCH, and DELETE.

REST Assured is simple to integrate with existing unit testing frameworks like JUnit and TestNG. In this tutorial will utilize TestNG with Rest Assured.

Q: What is the TestNG?
Ans:

  1. In TestNG, NG is for Next Generation. TestNG is an open-source automated TestNG framework.
  2. When actual development of the framework from scratch level is done TestNG framework plays a very important role.
  3. The limitations of the older framework were removed by the TestNG Framework.
  4. TestNG gave the ability to write flexible and significant tests to the developers with the help of annotations, sequencing, parametrizing, and grouping.

Refer Spring Boot TestNG Example/Tutorial for it's implementation.

Create Spring Boot Project from Spring Initializer

Project Structure

Spring Boot Rest Assured Example

Maven Dependency

All we need is spring-boot-starter-web, io.rest-assured for rest assured, org.testng for testng, and org.projectlombok dependency for auto generating getters/setters/constructor.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.techgeeknext</groupId>
	<artifactId>spring-boot-rest-assured</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-rest-assured</name>
	<description>Spring Boot + Rest Assured Example</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

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

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

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

		<!-- https://mvnrepository.com/artifact/org.testng/testng -->
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>7.3.0</version>
			<scope>test</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
		<dependency>
			<groupId>io.rest-assured</groupId>
			<artifactId>rest-assured</artifactId>
			<version>3.3.0</version>
			<scope>test</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.json/json -->
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20210307</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Rest Controller

Create rest endpoint to test the method using testNG + rest assured.

package com.techgeeknext.controller;

import com.techgeeknext.model.Employee;
import com.techgeeknext.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

//@CrossOrigin(origins = "http://localhost:8081")
@RestController
public class EmployeeController {

    @Autowired
    EmployeeRepository employeeRepository;

    /**
     * Get all the employees
     *
     * @return ResponseEntity
     */
    @GetMapping("/employees")
    public ResponseEntity<List<Employee>> getEmployees() {
        try {
            return new ResponseEntity<>(employeeRepository.findAll(), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Get the employee by id
     *
     * @param id
     * @return ResponseEntity
     */
    @GetMapping("/employee/{id}")
    public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") long id) {
        try {
            //check if employee exist in database
            Employee empObj = getEmpRec(id);

            if (empObj != null) {
                return new ResponseEntity<>(empObj, HttpStatus.OK);
            }

            return new ResponseEntity<>(HttpStatus.NOT_FOUND);

        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * Create new employee
     *
     * @param employee
     * @return ResponseEntity
     */
    @PostMapping("/employee")
    public ResponseEntity<Employee> newEmployee(@RequestBody Employee employee) {
        Employee newEmployee = employeeRepository
                .save(Employee.builder()
                        .name(employee.getName())
                        .role(employee.getRole())
                        .build());
        return new ResponseEntity<>(newEmployee, HttpStatus.OK);
    }


    /**
     * Method to get the employee record by id
     *
     * @param id
     * @return Employee
     */
    private Employee getEmpRec(long id) {
        Optional<Employee> empObj = employeeRepository.findById(id);

        if (empObj.isPresent()) {
            return empObj.get();
        }
        return null;
    }

}

Employee Model Object

package com.techgeeknext.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "employees")
public class Employee {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	@Column(name = "name")
	private String name;

	@Column(name = "role")
	private String role;
}

Rest assured test cases using TestNG

Create rest assured test class to test employee rest endpoints using TestNG.

package com.techgeeknext.controller;

import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.baseURI;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

public class EmployeeControllerTest {

    @BeforeAll
    public static void setup() {
        baseURI = "http://localhost:8080";
    }

    @Test
    public void testEmployeesStatus() {
        given().
                // baseUri("http://localhost:8080").
                when().
                get("/employees").
                then().
                log().all().
                assertThat().
                statusCode(200);
    }

    @Test
    public void testEmployeesResponseBody() {
        given().
                // baseUri("http://localhost:8080").
                        when().
                get("/employees").
                then().
                log().all().
                assertThat().
                statusCode(200).
                body("id", hasItems(1, 2),
                        "name", hasItems("User-1", "User-2"),
                        "role", hasItems("Admin", "Supervisor"),
                        "id[0]", equalTo(1),
                        "name[0]", is(equalTo("User-1")),
                        "size()", equalTo(2)
                );
    }

    @Test
    public void testGetEmployeeWithParam() {
        Response empResponse = given().
                // baseUri("http://localhost:8080").
                        contentType(ContentType.JSON).
                        pathParam("id", "1").
                        when().
                        get("/employee/{id}").
                        then().
                        log().all().
                        assertThat().
                        statusCode(200).
                        extract().
                        response();

        JsonPath jsonPathObj = empResponse.jsonPath();
        Assertions.assertEquals(jsonPathObj.getLong("id"), 1);
        Assertions.assertEquals(jsonPathObj.getString("name"), "User-1");
        Assertions.assertEquals(jsonPathObj.getString("role"), "Admin");
    }

    @Test
    public void extractGetEmployeesResponse() {
        Response res = given().
                // baseUri("http://localhost:8080").
                        when().
                        get("/employees").
                        then().
                        log().all().
                        assertThat().
                        statusCode(200).
                        extract().
                        response();
        System.out.println("response = " + res.asString());
    }

    @Test
    public void testPostEmployee() throws JSONException {
        JSONObject empParams = new JSONObject();
        empParams.put("name", "TechGeekNextUser44");
        empParams.put("role", "Supervisor");

        given()
                .contentType(ContentType.JSON)
                .body(empParams.toString())
                .log().all()

                .when()
                .post("http://localhost:8080/employee")

                .then()
                .assertThat().statusCode(200)
                .body("name", equalTo("TechGeekNextUser44"))
                .body("role", equalTo("Supervisor"))
                .log().all();

    }
}

Application Properties

Add h2 database connection details in application.properties file. Spring Boot makes it simple to set h2 properties in an application.properties file.

spring.datasource.url=jdbc:h2:file:~/employeetestdb;AUTO_SERVER=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.h2.console.settings.web-allow-others=true

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

Run the Rest Assured+ TestNG Test Class

  1. Start the Spring Boot Application by running spring-boot:run or by running main class.
  2. Add some data into h2 using POSTMAN Post rest endpoint to test it from rest assured as given in the code. Spring Boot Rest Assured Example
  3. Run RestAssured tests using TestNG : Right click on the project -> select Run -> Select All Tests option Spring Boot Rest Assured Example
  4. Rest Assured + TestNG Test Output: Spring Boot Rest Assured Example

Download Source Code

The full source code for this article can be found on below.
Download it here - Spring Boot Rest Assured Example


Recommendation for Top Popular Post :