Get List of Objects with TestRestTemplate

In this tutorial, you will learn how to use TestRestTemplate to get a list of objects. If you are also interested to learn how to send an HTTP POST request, then please have a look at the “TestRestTemplate HTTP Post Example” tutorial.

Maven Dependency

To use TestRestTemplate in your Spring Boot project, you should have the following dependency in the pom.xml file.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Inject TestRestTemplate into a Test Class

Using the @SpringBootTest annotation with an embedded server, you can inject the TestRestTemplate object into your test class with the @Autowired annotation.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UsersControllerIntegrationTest {

    @Autowired
    private TestRestTemplate testRestTemplate;

   ...

}

Prepare HTTP Headers

Sometimes we need to include HTTP Headers in our HTTP requests. This will help us provide the Authorization JWT token and tell the server about the content type we would like to get back. To prepare HTTP headers, we use HttpHeaders object.

 HttpHeaders headers = new HttpHeaders();
 headers.set("accept", "application/json");
 headers.set("Authorization", "Bearer JWT TOKEN HERE");

 HttpEntity requestEntity = new HttpEntity<>(null, headers);

Once you have HttpHeaders object ready, you will wrap it into HttpEntity object. You will then use HttpEntity in the HTTP GET request. Look at the How to Read HTTP Header tutorial to learn how to read Http Headers.

GET List of Objects

To send HTTP GET requests using TestRestTemplate, we can use the exchange() method.

 ResponseEntity<List<UserRest>> response = restTemplate.exchange("/users",
                HttpMethod.GET,
                requestEntity,
                new ParameterizedTypeReference<List<UserRest>>() {
                });

List<UserRest> users = response.getBody();

Where:

  • /users is a Web Service API endpoint that accepts HTTP GET requests and returns a list of objects,
  • HttpMethod.GET is the HTTP method used in the request,
  • requestEntity is a HttpEntity object that contains HttpHeaders,
  • UserRest – is a data type of an object that our /users API Endpoint returns.

Test Method Example

Below is an example of a test method that sends an HTTP GET request and receives back a list of objects.

@Test
@Order(4)
@DisplayName("GET /users works")
void testGetUsers_whenValidJWTProvided_returnsUsers() throws Exception {
    // Arrange
    String getUsersUrl = "http://localhost:" + localServerPort + "/users";
    HttpHeaders headers = new HttpHeaders();
    headers.set("accept", "application/json");
    headers.set("Authorization", authorizationHeader);

    HttpEntity requestEntity = new HttpEntity<>(null, headers);

    // Act
    ResponseEntity<List<UserRest>> response = restTemplate.exchange("/users",
            HttpMethod.GET,
            requestEntity,
            new ParameterizedTypeReference<List<UserRest>>() {
            });
    List<UserRest> users = response.getBody();

    // Assert
    assertTrue(response.getStatusCode().is2xxSuccessful(), "HTTP Response status code should be 200");
    assertTrue(users.size() == 1, "There should be exactly 1 user in the list");
}

Video Lessons

I hope this tutorial was of some value to you. If you like video tutorials, check my video course, “Testing Java with JUnit and Mockito“. This video course is for beginners; you do not need prior knowledge of testing Java applications to enrol.

Discover a wealth of tutorials dedicated to testing Spring Boot applications on the Testing Java Code page. Whether you’re new to Spring Boot testing or seeking advanced techniques, these tutorials provide valuable insights and strategies to effectively test your applications.

Happy learning!