What is TestRestTemplate and when would you use it in a Spring Boot test?
answer
- wraps RestTemplate, real HTTP
- @SpringBootTest RANDOM_PORT/DEFINED_PORT
- auto-configured bean, relative URLs
- full stack runs end-to-end
- no throw on 4xx/5xx
basics
~20 sTestRestTemplate is a Spring Boot helper for calling your own running app over real HTTP in a test. You use it with @SpringBootTest(webEnvironment = RANDOM_PORT) to send actual requests to an embedded server and check the responses.
solid answer
~40 sTestRestTemplate is a convenience wrapper around RestTemplate provided by spring-boot-test for integration tests. When you annotate a test with @SpringBootTest(webEnvironment = RANDOM_PORT) (or DEFINED_PORT), Spring Boot starts a real embedded servlet container and auto-configures a TestRestTemplate bean you can @Autowired. It sends genuine HTTP requests to your running app, so the full stack — controllers, filters, JSON serialization, Spring Security — actually executes. Its API mirrors RestTemplate (getForEntity, postForEntity, exchange). The auto-configured instance already knows the random port, so you call relative paths like "/api/users". The key difference from a plain RestTemplate is fault tolerance: it does not throw on 4xx/5xx responses, letting you assert on the returned status code directly.
code
java · 16 lines@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class UserApiIntegrationTest {
@Autowired
TestRestTemplate rest; // auto-configured, already knows the random port
@Test
void returnsUser() {
// relative path — no need to know the port
ResponseEntity<User> response =
rest.getForEntity("/api/users/1", User.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().name()).isEqualTo("Ada");
}
}go deeper
Know it calls your running app over real HTTP and is used with @SpringBootTest(webEnvironment = RANDOM_PORT).
Explain the auto-configuration, relative URLs, and that the full request pipeline (security, JSON) executes.
Contrast with MockMvc (no socket) and note the fault-tolerant error handling and blocking nature.
Position it in a test strategy: when a real socket adds value vs slice tests, and why teams may prefer WebTestClient going forward.
**TestRestTemplate** (`org.springframework.boot.test.web.client.TestRestTemplate`, shipped in `spring-boot-test`) is a helper designed for **integration tests that hit a genuinely running Spring Boot application over the network loopback**. ### The setup it belongs with You trigger a real server by choosing a web environment on `@SpringBootTest`: - `webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT` — starts the embedded servlet container (Tomcat by default) on a free random port. - `webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT` — starts it on the configured `server.port` (default 8080). Only in those two modes does Spring Boot **auto-configure a `TestRestTemplate` bean**. You inject it with `@Autowired`. ### What it actually does It wraps a `RestTemplate` and issues **real HTTP requests** to `http://localhost:<port>`. Because the request travels through the actual server socket, the *entire* production request pipeline runs: servlet filters, Spring Security, `DispatcherServlet`, `HandlerMapping`, your `@RestController`, `HttpMessageConverter` JSON (de)serialization, and exception handlers. This is a **black-box, end-to-end** test — the opposite of `MockMvc`, which drives a mocked servlet stack without a real socket. ### API surface Same method names as `RestTemplate`: - `getForEntity(url, Type.class)` → `ResponseEntity<Type>` - `getForObject(url, Type.class)` → just the body - `postForEntity`, `postForObject`, `put`, `delete` - `exchange(url, HttpMethod, HttpEntity, Type)` → the most flexible; lets you set headers and read status + headers + body. ### Relative URLs The auto-configured instance is pre-configured with the running server's base URI (via a `LocalHostUriTemplateHandler`), so you pass **relative paths** like `"/api/users/1"` — you do not need to know or hardcode the random port. If you build your own `new TestRestTemplate()` you must supply absolute URLs or the port yourself. ### Signature difference from RestTemplate It installs a no-op response error handler, so **4xx/5xx responses do not throw** — you assert on `response.getStatusCode()`. A plain `RestTemplate` would throw `HttpClientErrorException`/`HttpServerErrorException`. ### When to use it - End-to-end verification that a real request produces the right status/body, including security and serialization. - Older/imperative codebases (it is blocking and synchronous). ### When NOT to use it - Pure controller-layer tests without a real server → use `MockMvc` (`@WebMvcTest`). - New or reactive code, or when you want a fluent assertion DSL → `WebTestClient`. - `webEnvironment = MOCK` (the default) → no server is started, so TestRestTemplate has nothing to call.
- Which webEnvironment values make a TestRestTemplate bean available?RANDOM_PORT and DEFINED_PORT, because they start a real embedded server. MOCK (the default) and NONE do not start a server, so no TestRestTemplate is auto-configured.
- How does TestRestTemplate know which port to call when the port is random?The auto-configured bean is set up with a LocalHostUriTemplateHandler bound to the actual server port, so you pass relative paths and it prefixes localhost:<port> for you.
saying these in an interview costs you the question
- Thinking TestRestTemplate works with the default MOCK web environment (no real server is started there).
- Confusing it with MockMvc — TestRestTemplate makes real network calls; MockMvc drives a mock servlet stack.
- Believing you must hardcode the port for the auto-configured instance (it uses relative URLs).