TestRestTemplate helps you test your whole Spring Boot app by making real HTTP calls to your running server. It shows if your app works end-to-end.
TestRestTemplate for full integration in Spring Boot
@Autowired private TestRestTemplate restTemplate; ResponseEntity<Type> response = restTemplate.getForEntity("/api/path", Type.class);
Use @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) to start the server on a random port for testing.
TestRestTemplate is injected automatically by Spring Boot in test classes.
/hello endpoint and checks the response status and body.@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class MyIntegrationTest { @Autowired private TestRestTemplate restTemplate; @Test void testGet() { ResponseEntity<String> response = restTemplate.getForEntity("/hello", String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals("Hello World", response.getBody()); } }
newItem and expects a MyObject response.ResponseEntity<MyObject> response = restTemplate.postForEntity("/api/items", newItem, MyObject.class);
This full example shows a simple Spring Boot app with a /hello endpoint. The test uses TestRestTemplate to call the endpoint and check the response.
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello World"; } } @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class HelloControllerIntegrationTest { @Autowired private TestRestTemplate restTemplate; @Test void testHelloEndpoint() { ResponseEntity<String> response = restTemplate.getForEntity("/hello", String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals("Hello World", response.getBody()); } }
TestRestTemplate works only in tests with a running Spring Boot server.
Use webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT to avoid port conflicts.
You can test all HTTP methods: GET, POST, PUT, DELETE using TestRestTemplate methods.
TestRestTemplate lets you test your app like a real client using HTTP calls.
It helps verify your full app integration, not just parts of it.
Use it in Spring Boot tests with a running server on a random port.