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 be able to use TestRestTemplate in your Spring Boot project, you will need to have the following dependency in 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

If you are 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.

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,  then have a look at my video course called “Testing Java with JUnit and Mockito“. This video course is for absolute beginners and you do not need to have any prior knowledge of testing Java applications to enrol.

Happy learning!