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 Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Check whether Graph is Biconnected
Returning Custom Status Codes from Spring Controllers
Java Program to Implement Sorted Circular Doubly Linked List
Java Program to Check the Connectivity of Graph Using DFS
Java Program to Show the Duality Transformation of Line and Point
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
Java Program to Perform Finite State Automaton based Search
Java Program to Compute Cross Product of Two Vectors
HandlerAdapters in Spring MVC
Removing all Nulls from a List in Java
Java CyclicBarrier vs CountDownLatch
A Guide to EnumMap
Database Migrations with Flyway
Tìm hiểu về xác thực và phân quyền trong ứng dụng
Dynamic Proxies in Java
Java Program to Convert a Decimal Number to Binary Number using Stacks
Spring Security Custom AuthenticationFailureHandler
Java Program to Find Transitive Closure of a Graph
Hướng dẫn Java Design Pattern – Prototype
Tính kế thừa (Inheritance) trong java
New Features in Java 13
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Hướng dẫn sử dụng biểu thức chính quy (Regular Expression) trong Java
Iterable to Stream in Java
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Why String is Immutable in Java?
Java Program to Generate a Random Subset by Coin Flipping
Hướng dẫn Java Design Pattern – Observer
Java Program to Implement Binary Tree
Java Program to Compute the Area of a Triangle Using Determinants
Java Program to Implement Quick Sort Using Randomization