RESTful Services
RestTemplate
API Testing
Java
Spring Framework

RESTful Services test with RestTemplate

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

RestTemplate is a synchronous HTTP client, and it can be useful in tests for both calling a real local server and mocking remote HTTP responses. The key is to choose the right testing style. If you want to verify your own REST API end to end, use an integration test with a running Spring context. If you want to test code that depends on RestTemplate, use a mock server around the client instead.

Integration testing a real REST endpoint

For a Spring Boot application, an easy pattern is to start the server on a random port and call it through TestRestTemplate.

java
1import org.junit.jupiter.api.Test;
2import org.springframework.beans.factory.annotation.Autowired;
3import org.springframework.boot.test.context.SpringBootTest;
4import org.springframework.boot.test.web.client.TestRestTemplate;
5import org.springframework.http.ResponseEntity;
6
7import static org.assertj.core.api.Assertions.assertThat;
8
9@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
10class GreetingApiTest {
11
12    @Autowired
13    private TestRestTemplate restTemplate;
14
15    @Test
16    void returnsGreeting() {
17        ResponseEntity<String> response =
18                restTemplate.getForEntity("/api/greeting", String.class);
19
20        assertThat(response.getStatusCode().value()).isEqualTo(200);
21        assertThat(response.getBody()).contains("hello");
22    }
23}

This style is good when you want to verify request mapping, serialization, validation, and HTTP status codes together. Even though the title says RestTemplate, TestRestTemplate is the Spring Boot testing-friendly version of the same idea.

Testing client code that uses RestTemplate

If your application contains a service that calls an external REST API through RestTemplate, you usually do not want a real remote dependency in a unit test. In that case, wrap the RestTemplate with MockRestServiceServer.

java
1import org.junit.jupiter.api.Test;
2import org.springframework.http.HttpMethod;
3import org.springframework.http.MediaType;
4import org.springframework.test.web.client.MockRestServiceServer;
5import org.springframework.web.client.RestTemplate;
6
7import static org.assertj.core.api.Assertions.assertThat;
8import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
9import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
10import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
11
12class QuoteClientTest {
13
14    @Test
15    void fetchesQuote() {
16        RestTemplate restTemplate = new RestTemplate();
17        MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate);
18
19        server.expect(requestTo("https://example.test/api/quote"))
20              .andExpect(method(HttpMethod.GET))
21              .andRespond(withSuccess("{\"text\":\"be precise\"}", MediaType.APPLICATION_JSON));
22
23        QuoteClient client = new QuoteClient(restTemplate);
24        String result = client.fetchQuote();
25
26        assertThat(result).isEqualTo("be precise");
27        server.verify();
28    }
29}

This isolates the client behavior without needing a running external API. It is the right tool when the code under test is the HTTP consumer, not the server.

What should the test assert

Good REST tests usually verify more than just the response body. At minimum, consider:

  • HTTP status code
  • Response payload
  • Request method
  • Headers or content type when relevant
  • Error handling for failure responses

For client tests, verifying the outbound URL and method is often as important as verifying the parsed response.

Keep the test scope clear

Many weak tests mix two different goals:

  • Testing that your controller works
  • Testing that a client can call some other API

Those are different layers. If you blend them together, failures become harder to interpret. Use integration tests for your own HTTP endpoints and mock-server tests for outbound client code.

Common Pitfalls

The biggest mistake is using a real external service in a unit test. That makes tests slow, flaky, and dependent on network state outside your codebase.

Another issue is using RestTemplate integration tests when a controller-slice test would be enough, or vice versa. Choose the smallest test that still proves the behavior you care about.

Developers also forget to verify status codes and error cases. A test that checks only the happy-path response body often misses the most important behavior of a REST API.

Finally, be careful not to treat RestTemplate itself as the thing under test. Usually you are testing your controller, your client wrapper, or your serialization logic.

Summary

  • Use TestRestTemplate for integration tests against a running Spring Boot server.
  • Use MockRestServiceServer to test code that depends on RestTemplate.
  • Assert status codes, payloads, and important HTTP details.
  • Do not call real external services from fast unit tests.
  • Keep server tests and client tests as separate concerns.

Course illustration
Course illustration

All Rights Reserved.