In Spring Boot, @RestClientTest
is a specialized test annotation used for testing REST clients. It simplifies the setup of your test context and provides support for mocking and testing REST interactions with a RESTful web service. This tutorial will guide you through the process of setting up and using @RestClientTest
in a Spring Boot application.
Prerequisites
- JDK 17 or later
- Maven or Gradle
- IDE (IntelliJ IDEA, Eclipse, etc.)
Step 1: Set Up a Spring Boot Project
1.1 Create a New Spring Boot Project
Use Spring Initializr to create a new project with the following dependencies:
- Spring Web
- Spring Boot Test
Download and unzip the project, then open it in your IDE.
1.2 Configure application.properties
Set up the application properties for your project. This step is optional and only needed if you want to configure specific properties for your application.
# src/main/resources/application.properties
server.port=8080
Step 2: Create a REST Client
2.1 Create a Model Class
Create a model class that represents the data structure for your REST client.
package com.example.demo.model;
public class User {
private Long id;
private String name;
private String email;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2.2 Create a REST Client Service
Create a service class that uses RestTemplate
to make REST calls.
package com.example.demo.service;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class UserService {
private final RestTemplate restTemplate;
@Autowired
public UserService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public User getUserById(Long id) {
return restTemplate.getForObject("https://jsonplaceholder.typicode.com/users/" + id, User.class);
}
}
Explanation:
UserService
: A service class that uses RestTemplate
to fetch user data from a REST API.
getUserById(Long id)
: A method that makes a GET request to fetch user data by ID.
Step 3: Create a Test for the REST Client
3.1 Add Test Dependencies
Ensure you have the necessary test dependencies in your pom.xml
(for Maven) or build.gradle
(for Gradle).
For Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
For Gradle:
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.mockito:mockito-core'
3.2 Create a Test Class
Create a test class to test the UserService
using @RestClientTest
.
package com.example.demo.service;
import com.example.demo.model.User;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
@RestClientTest(UserService.class)
@Import(UserService.class)
class UserServiceTest {
@Autowired
private UserService userService;
@Autowired
private MockRestServiceServer server;
@MockBean
private RestTemplate restTemplate;
@Test
void getUserById_shouldReturnUser() {
// Arrange
User mockUser = new User();
mockUser.setId(1L);
mockUser.setName("John Doe");
mockUser.setEmail("john.doe@example.com");
String url = "https://jsonplaceholder.typicode.com/users/1";
Mockito.when(restTemplate.getForObject(url, User.class)).thenReturn(mockUser);
// Act
User user = userService.getUserById(1L);
// Assert
assertThat(user).isNotNull();
assertThat(user.getId()).isEqualTo(1L);
assertThat(user.getName()).isEqualTo("John Doe");
assertThat(user.getEmail()).isEqualTo("john.doe@example.com");
server.expect(ExpectedCount.once(), requestTo(url))
.andRespond(withSuccess());
}
}
Explanation:
@RestClientTest(UserService.class)
: Sets up a test context for the UserService
class and configures the necessary beans for testing REST clients.
@MockBean
: Creates a mock of the RestTemplate
bean.
MockRestServiceServer
: Allows setting up expectations on the requests that RestTemplate
will make and providing mock responses.
Mockito.when(restTemplate.getForObject(url, User.class)).thenReturn(mockUser)
: Mocks the getForObject
method of RestTemplate
to return a mockUser
object when the specified URL is called.
server.expect(ExpectedCount.once(), requestTo(url)).andRespond(withSuccess())
: Sets an expectation that the specified URL will be called once and responds with a success status.
Step 4: Running the Tests
4.1 Run the Tests
You can run the tests using your IDE or from the command line using Maven or Gradle.
For Maven:
./mvnw test
For Gradle:
./gradlew test
4.2 Verify the Test Results
Ensure that all tests pass successfully. The test should verify that the UserService
correctly interacts with the mocked REST API and returns the expected User
object.
Conclusion
In this tutorial, you have learned how to use @RestClientTest
to test REST clients in a Spring Boot application. This specialized test annotation simplifies the setup of your test context and provides support for mocking and testing REST interactions. By using MockRestServiceServer
and Mockito
, you can effectively test the behavior of your REST clients and ensure they work as expected.
Related Spring Boot Source Code Examples
Spring Boot Security Login REST API Example
Spring Boot Security Login and Registration REST API
Role-based Authorization using Spring Boot and Spring Security
Spring Boot JWT Authentication and Authorization Example
Spring Boot Security JWT Example - Login REST API with JWT Authentication
Spring Boot DTO Example
Spring Boot DTO ModelMapper Example
@GetMapping Spring Boot Example
@PostMapping Spring Boot Example
@PutMapping Spring Boot Example
@DeleteMapping Spring Boot Example
@PatchMapping Spring Boot Example
@SpringBootApplication - Spring Boot
Spring Boot Hello World REST API Example
Spring Boot REST API returns Java Bean
Create Spring Boot REST API returns List
Spring Boot REST API with Path Variable
Spring Boot REST API with Request Param
Spring Boot Hibernate MySQL CRUD REST API Tutorial
Spring Boot Real-Time Project Development using Spring MVC + Spring Security + Thymeleaf and MySQL Database
Spring Boot Tutorial - User Login and Registration Backend + Email Verification
Spring Boot JUnit and Mockito Example - Service Layer Testing
Spring Professional Certification Cost
Spring Boot Validate JSON Request Body
Spring Boot One to Many CRUD Example | REST Controller
Spring Boot Project with Controller Layer + Service Layer + Repository/DAO Layer
Spring Boot Reactive MongoDB CRUD Example - WebFlux
Spring Boot Amazon S3 - File Upload Download Delete Example
Spring Boot RabbitMQ Publisher and Consumer Example
Free Spring Boot Open Source Projects for Learning Purposes
Spring Boot + Microsoft SQL Server + Hibernate Example
Spring Boot Hibernate Thymeleaf MySQL CRUD Example
Spring Boot CRUD Example with Spring MVC, Spring Data JPA, ThymeLeaf, Hibernate, MySQL
Spring Boot Hibernate RESTful GET POST PUT and DELETE API Tutorial
Best YouTube Channels to learn Spring Boot
React Spring Boot Example
Spring Boot Groovy Thymeleaf Example Tutorial
Spring Boot Scala Thymeleaf Example Tutorial
Spring Boot Hibernate DAO with MySQL Database Example
Spring Boot PostgreSQL CRUD Example
Spring Boot CRUD Example with MySQL
Spring Boot Starter Parent
Spring Boot JdbcTemplate Example
Spring Boot PayPal Payment Gateway Integration Example
Create Spring Boot REST API
How to Create Spring Boot Application Using Maven
How to Create Spring Boot Application Using Gradle
How to Use Thymeleaf in a Spring Boot Web Application?
How to Enable CORS in a Spring Boot Application?
Spring Boot + Angular 8 CRUD Example
Spring Boot + Angular 9 CRUD Example
Spring Boot + Angular + WebSocket Example
Spring Boot CRUD Application with Thymeleaf
Spring Boot ReactJS CRUD Project - Employee Management App | GitHub
Spring Petclinic ReactJS Project | GitHub
Spring Boot React JWT Authentication Example
Spring Boot React Basic Authentication Example
CRUD Example using Spring Boot + Angular + MySQL
Spring Boot + React + Redux CRUD Example
Spring Boot Project - Sagan
Spring Boot Project - ReactJS Spring Boot CRUD Full Stack Application - GitHub
Spring Boot Project - Spring Initializr
Spring Boot + Angular Project - Employee Management System
Spring Boot Thymeleaf Project - Employee Management System
Spring Boot MVC Project - Blogs Aggregator
Spring Boot Project - Spring Petclinic | GitHub
Spring Boot, Spring Cloud Microservice Project - PiggyMetrics | GitHub
Spring Boot, Spring Security, JWT, React, and Ant Design - Polling App | GitHub
Spring Boot Microservice Project - Shopping Cart App | GitHub
Spring Boot, Spring Cloud Microservice Project - Spring Petclinic App | GitHub
Microservices with Spring Cloud Project | GitHub
Spring Boot Angular Petclinic Project | GitHub
Spring Boot Angular Project - BookStore App | GitHub
React Springboot Microservices Project | GitHub
Spring Boot Microservices, Spring Cloud, and React Project - BookStoreApp | GitHub
Spring Boot + Spring Security + JWT Example
Spring Boot Hibernate Assign UUID Identifiers Example
Spring Boot Angular Project - Reddit Clone Application
Spring Boot Step-by-Step Example
Spring Boot Starters List
Spring Boot E-Commerce Project - Shopizer
Spring Data JPA - save() Method Example
Spring Data JPA - saveAll() Method Example
Spring Data JPA - findById() Method Example
Spring Data JPA - findAll() Method Example
Spring Data JPA - count() Method Example
Spring Data JPA - deleteById() Method Example
Spring Data JPA - delete() Method Example
Spring Data JPA - deleteAll() Method Example
Spring Data JPA - Distinct Query Method Example
Spring Data JPA - GreaterThan Query Method Example
Spring Data JPA - LessThan Query Method Example
Spring Data JPA - Containing Query Method Example
Spring Data JPA - Like Query Method Example
Spring Data JPA - Between Query Method Example
Spring Data JPA - Date Range Between Query Method Example
Spring Data JPA - In Clause Query Method Example
Unit Test Spring Boot GET REST API using JUnit and Mockito
Unit Test Spring Boot POST REST API using JUnit and Mockito
Unit Test Spring Boot PUT REST API using JUnit and Mockito
Unit Test Spring Boot DELETE REST API using JUnit and Mockito
Create REST Client using WebClient for Spring Boot CRUD REST API
Spring Boot WebClient GET Request with Parameters
Spring Boot WebClient POST Request Example
Spring Boot WebClient PUT Request Example
Spring Boot WebClient DELETE Request Example
Spring Boot RestClient GET Request Example
Spring Boot RestClient POST Request Example
Spring Boot RestClient PUT Request Example
Spring Boot RestClient Delete Request Example
Spring Core Annotations with Examples
Spring Boot @Component Example
Spring Boot @Autowired Example
Spring Boot @Qualifier Example
Spring Boot @Primary Example
Spring Boot @Bean Example
Spring Boot @Lazy Example
Spring Boot @Scope Example
Spring Boot @PropertySource Example
Spring Boot @Transactional Example
Spring Boot @Configuration Example
Spring Boot @ComponentScan Example
Spring Boot @Profile Example
Spring Boot @Cacheable Example
Spring Boot @DependsOn Example
Spring Boot @RestController Example
Spring Boot @ResponseBody Example
Spring Boot @GetMapping Example
Spring Boot @PostMapping Example
Spring Boot @PutMapping Example
Spring Boot @DeleteMapping Example
Spring Boot @PatchMapping Example
Spring Boot @PathVariable Example
Spring Boot @ResponseStatus Example
Spring Boot @Service Example
Spring Boot @Repository Example
Spring Boot @RequestParam Example
Spring Boot @SessionAttribute Example
Spring Boot @RequestBody Example
Spring Boot @ExceptionHandler Example
Spring Boot @InitBinder Example
Spring Boot @ModelAttribute Example
Spring Boot @RequestMapping Example
Spring Boot @CrossOrigin Example
Spring Boot @ControllerAdvice Example
Spring Boot @RestControllerAdvice Example
Spring Boot @SpringBootApplication Example
Spring Boot @EnableAutoConfiguration Example
Spring Boot @ConditionalOnClass Example
Spring Boot @SpringBootConfiguration Example
Spring Boot @ConditionalOnProperty Example
Spring Boot @ConditionalOnWebApplication Example
Spring Boot @ConfigurationProperties Example
Spring Boot @Async Example
Spring Boot @Scheduled Example
Spring Boot @SpringBootTest Example
Spring Boot @WebMvcTest Example
Spring Boot @DataJpaTest Example
Spring Boot @EnableDiscoveryClient Example
Spring Boot @EnableFeignClients Example
Spring Boot @RefreshScope Example
Spring Boot @LoadBalanced Example
Spring Boot @Query Example
Spring Boot @Modifying Example
Spring Boot @Param Example
Spring Boot JPA @Transient Example
Spring Boot JPA @Enumerated Example
Spring Boot JPA @Temporal Example
Spring Boot @CreatedBy Example
Spring Boot @LastModifiedDate Example
Spring Boot @IdClass Example
Spring Boot
Comments
Post a Comment