Exploring the Spring Boot TestRestTemplate

1. Overview

This article explores the Spring Boot TestRestTemplate. It can be treated as a follow-up of The Guide to RestTemplate, which we firmly recommend to read before focusing on TestRestTemplateTestRestTemplate can be considered as an attractive alternative of RestTemplate.

2. Maven Dependencies

To use TestRestTemplate, you are required to have an appropriate dependency like:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-test</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

You can find the latest version on Maven Central.

3. TestRestTemplate and RestTemplate

Both of these clients are quite suitable for writing integration tests and can handle communicating with HTTP APIs very well.

For example, they provide us with the same methods standard methods, headers, and other HTTP constructs.

And all of these operations are well described in The Guide to RestTemplate, so we won’t revisit them here.

Here’s a simple GET request example:

TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.
  getForEntity(FOO_RESOURCE_URL + "/1", String.class);
 
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

Despite the fact that both classes are very similar, TestRestTemplate does not extend RestTemplate and does offer a few very exciting new features.

4. What’s New in TestRestTemplate?

4.1. Constructor With Basic Auth Credentials

TestRestTemplate provides a constructor with which we can create a template with specified credentials for basic authentication.

All requests performed using this instance will be authenticated using provided credentials:

TestRestTemplate testRestTemplate
 = new TestRestTemplate("user", "passwd");
ResponseEntity<String> response = testRestTemplate.
  getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class);
 
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

4.2. Constructor With HttpClientOption

TestRestTemplate also enables us to customize the underlying Apache HTTP client using the HttpClientOption which is an enum in TestRestTemplate with the following options: ENABLE_COOKIES, ENABLE_REDIRECTS, and SSL.

Let’s see a quick example:

TestRestTemplate testRestTemplate = new TestRestTemplate("user", 
  "passwd", TestRestTemplate.HttpClientOption.ENABLE_COOKIES);
ResponseEntity<String> response = testRestTemplate.
  getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class);
 
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK))

In the above example, we’re using the options together with Basic Authentication.

If we don’t need authentication, we still can create a template with a simple constructor:

TestRestTemplate(TestRestTemplate.HttpClientOption.ENABLE_COOKIES)

4.3. New Method

Not only can constructors create a template with specified credentials. We can also add credentials after our template is created. TestRestTemplate gives us a method withBasicAuth() which adds credentials to an already existing template:

TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.withBasicAuth(
  "user", "passwd").getForEntity(URL_SECURED_BY_AUTHENTICATION, 
  String.class);
 
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

5. Using Both TestRestTemplate and RestTemplate

TestRestTemplate can work as a wrapper for RestTemplate, e.g. if we are forced to use it because we are dealing with legacy code. You can see below how to create such a simple wrapper:

RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.configure(restTemplate);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
ResponseEntity<String> response = testRestTemplate.getForEntity(
  FOO_RESOURCE_URL + "/1", String.class);
 
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));

6. Conclusion

TestRestTemplate is not an extension of RestTemplate, but rather an alternative that simplifies integration testing and facilitates authentication during tests. It helps in customization of Apache HTTP client, but also it can be used as a wrapper of RestTemplate.

You can check out the examples provided in this article over on GitHub.

Related posts:

Java Program to Create the Prufer Code for a Tree
Database Migrations with Flyway
Java Program to Implement Find all Cross Edges in a Graph
Java Program to Implement Pairing Heap
XML-Based Injection in Spring
Using Custom Banners in Spring Boot
Deploy a Spring Boot WAR into a Tomcat Server
Java Program to Implement Hash Tables Chaining with List Heads
Java Program to implement Bit Matrix
Transaction Propagation and Isolation in Spring @Transactional
Introduction to Spring Cloud CLI
Introduction to Spliterator in Java
Java Program to Implement Fibonacci Heap
Java Program to Check the Connectivity of Graph Using BFS
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
New in Spring Security OAuth2 – Verify Claims
Java Program to Implement TreeMap API
Checking for Empty or Blank Strings in Java
Java – InputStream to Reader
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Implement Sorted Array
Spring Boot - Securing Web Applications
Java Program to implement Associate Array
Một số ký tự đặc biệt trong Java
Using Java Assertions
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
Hướng dẫn Java Design Pattern – Service Locator
Spring WebClient and OAuth2 Support
Spring’s RequestBody and ResponseBody Annotations
Java Program to Generate Randomized Sequence of Given Range of Numbers
Java Program to Implement Binary Search Tree
Java Program to Find Nearest Neighbor Using Linear Search