TestRestTemplate for Full Integration Testing in Spring Boot
📖 Scenario: You are building a simple Spring Boot application that manages a list of books. You want to test the full integration of your REST API endpoints to make sure they work correctly from end to end.
🎯 Goal: Create a Spring Boot integration test using TestRestTemplate to verify the REST API endpoints for adding and retrieving books.
📋 What You'll Learn
Create a simple Book class with id and title fields
Create a REST controller with endpoints to add and get books
Configure TestRestTemplate in the test class
Write integration tests that use TestRestTemplate to call the REST endpoints
💡 Why This Matters
🌍 Real World
Integration tests ensure your REST API works correctly when all parts run together, just like real users would use it.
💼 Career
Spring Boot developers often write integration tests with TestRestTemplate to catch bugs early and deliver reliable APIs.
Progress0 / 4 steps
1
Create the Book class
Create a Java record called Book with two fields: Long id and String title.
Spring Boot
Hint
A record is a simple way to create immutable data classes in Java 17+. Use the syntax public record Book(Long id, String title) {}.
2
Create the REST controller
Create a Spring REST controller class called BookController with a List<Book> books field initialized as an empty ArrayList. Add two endpoints: a @PostMapping("/books") method addBook that takes a @RequestBody Book book and adds it to books, and a @GetMapping("/books") method getBooks that returns the list books.
Spring Boot
Hint
Use @RestController to create the controller. Initialize books as new ArrayList<>(). Use @PostMapping and @GetMapping annotations for the methods.
3
Configure TestRestTemplate in the test class
Create a test class called BookControllerIntegrationTest annotated with @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT). Inject a TestRestTemplate field called restTemplate using @Autowired.
Spring Boot
Hint
Use @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) to start the server on a random port. Inject TestRestTemplate with @Autowired.
4
Write integration tests using TestRestTemplate
In BookControllerIntegrationTest, add a test method testAddAndGetBooks annotated with @Test. Use restTemplate.postForEntity("/books", new Book(1L, "Spring Boot Guide"), Void.class) to add a book. Then use restTemplate.getForObject("/books", Book[].class) to get the books array. Assert that the array length is 1 and the first book's title is "Spring Boot Guide".
Spring Boot
Hint
Use restTemplate.postForEntity to send a POST request and restTemplate.getForObject to send a GET request. Use JUnit assertions to check the results.
Practice
(1/5)
1. What is the main purpose of TestRestTemplate in a Spring Boot application?
easy
A. To perform real HTTP requests for full integration testing
B. To mock database calls during unit tests
C. To replace the main application context
D. To generate API documentation automatically
Solution
Step 1: Understand TestRestTemplate's role
TestRestTemplate is designed to send HTTP requests to the running Spring Boot app during tests.
Step 2: Compare with other testing tools
Unlike mocks or stubs, it tests the full app stack by making real HTTP calls.
Final Answer:
To perform real HTTP requests for full integration testing -> Option A
Quick Check:
TestRestTemplate = real HTTP requests [OK]
Hint: Remember: TestRestTemplate tests full app via HTTP [OK]
Common Mistakes:
Confusing TestRestTemplate with mocking tools
Thinking it replaces application context
Assuming it auto-generates docs
2. Which annotation combination is correct to enable TestRestTemplate with a random port in a Spring Boot test?
easy
A. @SpringBootTest(webEnvironment = WebEnvironment.MOCK)
B. @SpringBootTest(webEnvironment = WebEnvironment.NONE)
C. @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
D. @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
Solution
Step 1: Identify webEnvironment for real HTTP tests
Using RANDOM_PORT starts the server on a random port for real HTTP calls.
Hint: NullPointer on restTemplate means missing @SpringBootTest [OK]
Common Mistakes:
Blaming missing endpoint for NullPointerException
Assuming serialization error causes NPE
Forgetting to add @Test annotation
5. You want to write a full integration test using TestRestTemplate that posts JSON data to /api/items and verifies the created item's ID is returned. Which code snippet correctly performs this test?
hard
A. var item = new Item(null, "Book");
var response = restTemplate.postForEntity("/api/items", item, Item.class);
assertEquals(201, response.getStatusCodeValue());
assertNotNull(response.getBody().getId());
B. var item = new Item(null, "Book");
var response = restTemplate.getForEntity("/api/items", Item.class);
assertEquals(201, response.getStatusCodeValue());
C. var item = new Item(null, "Book");
var response = restTemplate.postForObject("/api/items", item, Item.class);
assertEquals(404, response.getStatusCodeValue());
D. var item = new Item(null, "Book");
var response = restTemplate.exchange("/api/items", HttpMethod.GET, null, Item.class);
assertEquals(201, response.getStatusCodeValue());
Solution
Step 1: Identify correct HTTP method for creating resource
POST is used to create new items, so postForEntity is appropriate.
Step 2: Verify response status and body
201 status means created; response body should contain new item's ID, so assertNotNull on getId() is correct.
Final Answer:
Code snippet using postForEntity with POST and checking 201 and ID -> Option A
Quick Check:
POST + 201 + returned ID = correct test [OK]
Hint: Use postForEntity and check 201 plus returned ID [OK]
Common Mistakes:
Using GET instead of POST for creation
Expecting 404 instead of 201 status
Using postForObject without status check
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.