Step-by-Step Implementation of @RestClientTest in Spring Boot
Below are the steps to implement @RestClientTest in Spring Boot.
Step 1: Maven dependencies
Add the spring-boot-starter-test starter module into the pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Step 2: Add Spring Boot to the Project
First, we need to make sure that our project is using Spring Boot 1.4.x or higher:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Step 3: RestTemplateBuilder-using testing service
We may apply the @RestClientTest annotation directly over the test class if the service under test utilizes RestTemplateBuilder to obtain the RestTemplate for calling external services.
Java
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.beans.factory.annotation.Autowired; import com.springexamples.demo.service.UserService; @Service public class UserServiceImpl implements UserService { private final RestTemplate restTemplate; // Constructor with RestTemplateBuilder injection @Autowired public UserServiceImpl(RestTemplateBuilder restTemplateBuilder) { this .restTemplate = restTemplateBuilder.build(); } @Override public String testUserService() { // URL of the REST endpoint final String uri = "http://localhost:8080/users" ; // Making a GET request to the specified URI and expecting a response of type String String result = restTemplate.getForObject(uri, String. class ); // Printing the result to the console (you might want to log it instead) System.out.println(result); // Returning the result return result; } } |
Step 4: Configure RestTemplateBuilder
Spring Boot uses both auto-configured RestTemplateBuilder to simplify creating RestTemplates. Also, it matches the @RestClientTest annotation to test the clients built with RestTemplateBuilder. Here is how we can create a simple REST client with RestTemplateBuilder auto injected for us.
Java
@Service public class DetailsServiceClient { private final RestTemplate restTemplate; // Constructor that injects RestTemplateBuilder public DetailsServiceClient(RestTemplateBuilder restTemplateBuilder) { restTemplate = restTemplateBuilder.build(); } // Method to retrieve user details from the Details service public Details getUserDetails(String name) { // Using RestTemplate to make a GET request to the Details service // The response is expected to be converted into a Details object return restTemplate.getForObject( "/{name}/details" , Details. class , name); } } |
Step 5: Build @RestClientTest
@RestClientTest adds pre-configured RestTemplateBuilder and MockRestServiceServer objects to the context and makes ensuring that Jackson and GSON support is auto configured. The @RestClientTest annotation’s value or components element is used to specify the bean that is being tested:
Java
@RunWith (SpringRunner. class ) @RestClientTest (DetailsServiceClient. class ) public class DetailsServiceClientTest { @Autowired private DetailsServiceClient client; @Autowired private MockRestServiceServer server; @Autowired private ObjectMapper objectMapper; @Before public void setUp() throws Exception { // Creating a Details object and converting it to a JSON string String detailsString = objectMapper.writeValueAsString( new Details( "Dido Pal" , "dido" )); // Setting up expectations for a request to the specified URL this .server.expect(requestTo( "/dido/details" )) .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); } @Test public void whenCallingGetUserDetails_thenClientMakesCorrectCall() throws Exception { // Calling the getUserDetails method on the client Details details = this .client.getUserDetails( "dido" ); // Assertions to verify the correctness of the response assertThat(details.getLogin()).isEqualTo( "dido" ); assertThat(details.getName()).isEqualTo( "Dido Pal" ); } } |
- First, we may define the precise service that is being tested using the @RestClientTest annotation; in this example, that is the DetailsServiceClient class. Everything else will be filtered out and this service loaded into the test context.
- This speeds up the loading of the context by allowing us to autowire the DetailsServiceClient object within our test and keep everything else outside.
- After that, we can just inject and utilize the MockRestServiceServer instance as it is also set up for a @RestClientTest-annotated test (and tied to the DetailsServiceClient instance for us).
- Finally, we can inject Jackson’s ObjectMapper instance to prepare the take response value for the MockRestServiceServer thanks to JSON support for @RestClientTest.
@RestClientTest in Spring Boot
Annotation for a Spring Rest Client Test limited to beans using RestClient.Builder or RestTemplateBuilder. By using this annotation, complete auto-configuration will be disabled and only configuration applicable to the rest client tests (i.e., @JsonComponent beans and Jackson or GSON auto-configuration, but not standard @Component beans) will be applied. By default, a MockRestServiceServer will also be automatically configured for tests marked with RestClientTest.
The @AutoConfigureMockRestServiceServer annotation may be utilized for more precise control. We may include @AutoConfigureWebClient(registerRestTemplate=true) if we are testing a bean that injects a RestTemplate directly rather than using RestTemplateBuilder.
Contact Us