0
0
Spring Bootframework~30 mins

TestRestTemplate for full integration in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use restTemplate.postForEntity to send a POST request and restTemplate.getForObject to send a GET request. Use JUnit assertions to check the results.