Horje
How to Configure Spring Boot TestRestTemplate?

The Spring Framework is an open-source framework for creating applications, providing many annotations and features to make development easier. Spring Boot simplifies the setup and development of the Spring applications. One useful utility for testing RESTful web services in Spring Boot is TestRestTemplate, which provides additional features such as auto-configuration and simplified initialization.

Configure Spring Boot TestRestTemplate

dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
@SpringBootTest
public class MyRestControllerTest {
@Autowired
private TestRestTemplate testRestTemplate;

@Test
public void exampleTest() {
// Use testRestTemplate here
}
}


Functionality of TestRestTemplate

  • Auto-Configuration: Automatically configured based on application context
  • Simplified Initialization: Here No need manual Setup.
  • Cookie Management: Handles cookies for session management automatically.
  • Basic Authentication: Simplified support for basic authentication.

Where It Is Used:

The TestRestTemplate primarily used in integration testing where we need to interact with our RESTful web services. It is useful in scenarios such as,

  • Testing REST endpoints
  • Verify HTTP response and Status code
  • Ensuring correct serialization and de-serialization of JSON data
  • Testing secured endpoints with authentication

Prerequisites:

  • Java Programming
  • Gradle Tool
  • Spring Framework
  • Spring Testing
  • Test Rest Template
  • STS IDE

Tools and Technologies:

  • Java Programming
  • Gradle Tool
  • Spring Framework
  • Spring Testing
  • REST APIs

Dependencies:

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}


Project Folder Structure:

Project Folder Structure


Steps to Configure Spring Boot TestRestTemplate

Here,we created a simple Spring Project with Gradle tool with required gradle dependencies for the project.

Step 1: Create a Rest Controller

Once Project is successfully created, create one class in the main package of the project with name MyRestController and This class annotated with @RestController.

This class is used for defining the API end points. Here we created a sayHello() which has return type has ResponseEntity. This API return a ResponseEntity object as output while hitting this api endpoint.

MyRestController.java:

Java
package com.app;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class MyRestController {

    @GetMapping("/hello")
    public ResponseEntity<String> sayHello() {
        return ResponseEntity.ok("Hello, World!");
    }
}


This class defines a REST API endpoint /api/hello that returns a ResponseEntity with the message “Hello, World!”.

Step 2: Create the Test Class

Now go to testing folder in the spring project. It is located at src/test/java by default the spring framework create a test class in this package. In this class we write our logic. First Setup Web Environment port in the @SpringBootTest annotation.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

After that We Autowired the TestRestTemplate by using @Autowired annotation. RestTemplate that simplifies testing by providing additional features such as auto-configuration and simplified initialization. After this we created a test method testSayHello() by using @Test annotation. In that method we define the required logic.

ResponseEntity<String> response = testRestTemplate.getForEntity("/api/hello", String.class);

This method first get response from the /api/hello api, Then check the HttpStatus code If It is equal then we return ResponseEntity object as output.

TestRestTemplateApplicationTests.java:

Java
package com.app;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TestRestTemplateApplicationTests {

    @Test
    void contextLoads() {
    }

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Test
    public void testSayHello() {
        ResponseEntity<String> response = testRestTemplate.getForEntity("/api/hello", String.class);
        assertEquals(HttpStatus.OK, response.getStatusCode());
        assertEquals("Hello, World!", response.getBody());
    }
}


This test class uses TestRestTemplate to test the /api/hello endpoint. It asserts that the response status is 200 OK and the response body is “Hello, World!”.

Step 3: Run the Application

Once all the test cases and required business logic is developed, then run this project as Spring Boot App. By default this project runs on port number 8080 with Tomcat server.

Application Runs


Step 4: Run the Tests

Now, run this project as Junit Test. If there is no errors then we will get the below output, otherwise we will get error in the Java console.

Running the Tests


Step 5: Test the API

APIs Testing:

The Hello API is a GET Mapping HTTP request. While the end user while hit this API, this API returns a ResponseEntity as output.

http://localhost:8080/api/hello
@GetMapping("/hello")
public ResponseEntity<String> sayHello() {
return ResponseEntity.ok("Hello, World!");
}

When we hit this API, we will get the below output.

Output:

Browser Output


By following the steps outlined above, you can easily configure and use TestRestTemplate in your projects, ensuring robust and reliable REST API testing.





Reffered: https://www.geeksforgeeks.org


Advance Java

Related
How to Create and Setup Spring Boot Project in VSCode? How to Create and Setup Spring Boot Project in VSCode?
Eureka vs Consul: Service Registry Comparison Eureka vs Consul: Service Registry Comparison
Difference between Role and GrantedAuthority in Spring Security Difference between Role and GrantedAuthority in Spring Security
Maven Compiler Plugin Maven Compiler Plugin
Exclude a Dependency in a Maven Plugin Exclude a Dependency in a Maven Plugin

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17