Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 78

Application Integration Testing with Spring Boot and Testcontainers

This lesson is built with resources from youtube.com, blog.jetbrains.com and 1 more site.

Hello! Welcome to the final lesson of the "Testing and Integrating the Full System" module.

In our previous lessons, we've systematically built up our testing strategy. We started with isolated controller tests using @WebMvcTest and then moved to data layer tests with @DataJpaTest. You learned how @DataJpaTest provides a fast and convenient way to test repositories using an in-memory H2 database, but we also highlighted its biggest weakness: an in-memory database isn't a perfect replica of your production database.

Today, we address that weakness head-on. Our goal is to write a full application integration test using @SpringBootTest and Testcontainers to verify an API flow against a real PostgreSQL database. This is the highest level of automated backend testing, ensuring all layers of your application work together correctly with production-like dependencies.

Why Full Integration Testing with Testcontainers?

In a full integration test, we load the entire Spring application context—controllers, services, repositories, and all other components. We then test a complete use case, from an incoming HTTP request to data being persisted in a database, and the HTTP response being sent back.

By using Testcontainers, we replace the in-memory H2 database with a genuine PostgreSQL database running inside a temporary Docker container. This gives us maximum confidence that our application will behave the same way in production.

Spring Boot Integration Testing with Testcontainers
This diagram shows the core idea of Testcontainers. Your Spring Boot integration tests use the Testcontainers library to programmatically start, communicate with, and shut down real services (like PostgreSQL or Kafka) running in Docker containers.

MERN-to-Spring Mapping: Production Parity in Testing

In the MERN world, you might run tests against a mongodb-memory-server for speed. However, you've likely encountered situations where a complex aggregation pipeline or a specific index behavior works differently on the in-memory version versus your production Atlas cluster.

Testcontainers solves this problem by essentially automating docker run postgres for your test suite. It provides a real, ephemeral database instance for each test run, ensuring your tests are executed against the exact same database technology you use in production.


What is Testcontainers?

Testcontainers is a Java library that makes it easy to use Docker containers as ephemeral dependencies for your tests. It manages the entire lifecycle of the container: pulling the image, starting it, waiting for it to be ready, providing connection details to your application, and stopping/removing it after the tests are done.

Let's start with a quick video to see what Testcontainers is and why it's so powerful.

Spring Boot Testcontainers - Integration Testing made easy!

This video from Dan Vega provides a concise and practical introduction to Testcontainers.

Watch the first 2 minutes (00:00 to 02:03). Dan explains the core value proposition of Testcontainers: making it easy to write tests against real, production-like dependencies.


Setting Up Your Project for Testcontainers

To use Testcontainers in our Spring Boot project, we need to add a few dependencies to our pom.xml.

  1. testcontainers BOM: A Bill of Materials to manage versions for all Testcontainers modules.
  2. junit-jupiter: The Testcontainers integration for JUnit 5.
  3. postgresql: The specific module for PostgreSQL.
  4. spring-boot-testcontainers: A special Spring Boot dependency that enables amazing auto-configuration features.

Here's what the dependency section of your pom.xml should look like:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>testcontainers-bom</artifactId>
            <version>1.19.8</version> <!-- Use a recent version -->
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <!-- ... other dependencies ... -->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- Add these for Testcontainers -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-testcontainers</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testcontainers</groupId>
        <artifactId>junit-jupiter</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testcontainers</groupId>
        <artifactId>postgresql</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

After adding these dependencies and reloading your Maven project, you're ready to write your first full integration test.


Hands-On: A Full API Integration Test

We will write a test for our PostController to verify the "create post" API endpoint. This test will:

  1. Start the entire Spring Boot application.
  2. Spin up a real PostgreSQL container.
  3. Automatically connect the application to that container.
  4. Make an HTTP POST request to /api/posts.
  5. Verify the HTTP response and check that the data was correctly saved in the database.

Create a new test class PostControllerIntegrationTest.java.

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.assertj.core.api.Assertions.assertThat;

// 1. Load the full application context and run on a random port
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
// 2. Enable Testcontainers JUnit 5 support
@Testcontainers
class PostControllerIntegrationTest {

    // 3. Define the PostgreSQL container
    @Container
    @ServiceConnection // 4. THE MAGIC: Auto-configures the connection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private PostRepository postRepository;
    
    @Autowired
    private UserRepository userRepository;

    @BeforeEach
    void setUp() {
        // Clean up tables before each test to ensure isolation
        postRepository.deleteAll();
        userRepository.deleteAll();
    }

    @Test
    void shouldCreatePost() {
        // --- Arrange ---
        // First, create a user to be the author of the post
        User author = new User("testuser", "test@example.com", "password");
        User savedAuthor = userRepository.save(author);

        PostRequestDto postRequest = new PostRequestDto("My First Post", "This is the content.", savedAuthor.getId());

        // --- Act ---
        ResponseEntity<PostResponseDto> response = restTemplate.postForEntity(
                "/api/posts",
                postRequest,
                PostResponseDto.class
        );

        // --- Assert ---
        // Assert HTTP status
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);

        // Assert response body
        PostResponseDto createdPost = response.getBody();
        assertThat(createdPost).isNotNull();
        assertThat(createdPost.id()).isNotNull();
        assertThat(createdPost.title()).isEqualTo("My First Post");

        // Assert data was saved in the database
        assertThat(postRepository.count()).isEqualTo(1);
        Post persistedPost = postRepository.findAll().get(0);
        assertThat(persistedPost.getAuthor().getId()).isEqualTo(savedAuthor.getId());
    }
}

Code Breakdown:

  1. @SpringBootTest(webEnvironment = ...): Unlike @WebMvcTest or @DataJpaTest, this annotation bootstraps your entire application. RANDOM_PORT starts a real web server on a random available port, making your test feel like a real running application.
  2. @Testcontainers: This JUnit 5 annotation scans your test class for fields annotated with @Container and manages their lifecycle.
  3. @Container: This marks the PostgreSQLContainer field as a container to be managed by the Testcontainers extension. It will be started before any tests run and stopped after they all complete.
  4. @ServiceConnection: This is a powerful feature from Spring Boot 3.1+. It automatically detects the running container, gets its dynamic JDBC URL, username, and password, and configures your application's DataSource to connect to it. This replaces several lines of manual boilerplate configuration (@DynamicPropertySource).

The following blog post provides an excellent written walkthrough of this entire process, which you can use as a reference.

Testing Spring Boot Applications Using Testcontainers

The article "Testing Spring Boot Applications Using Testcontainers" from the JetBrains blog is a perfect companion to this lesson. It covers the setup and shows clear examples for both repository and full API tests.

Focus on the sections "Integration testing Spring Boot applications using Testcontainers" and "Testing Spring Boot REST APIs". Notice how they build up from a repository test to a full @SpringBootTest, and pay close attention to the use of @ServiceConnection and TestRestTemplate.


Debugging-First: What Can Go Wrong?

Integration tests are powerful, but because they involve more moving parts, they can be tricky to debug. Here are common issues and how to fix them.

  • Issue: Connection refused error on startup.

    • Meaning: Your Spring application failed to connect to the PostgreSQL container.
    • Root Cause: This almost always means the DataSource properties (spring.datasource.url, etc.) were not correctly overridden.
    • Solution:
      1. Ensure you are using Spring Boot 3.1+ and have the spring-boot-testcontainers dependency.
      2. Make sure the @ServiceConnection annotation is on your @Container field.
      3. If you see examples using @DynamicPropertySource, understand that this was the manual way to do what @ServiceConnection now does automatically. While it's good to recognize, prefer @ServiceConnection in new code.
  • Issue: Tests are slow to start.

    • Meaning: Starting a Docker container for the first time involves pulling the image and initializing the database, which can take 10-20 seconds.
    • Solution (for local development): Testcontainers has a "reuse" feature. You can enable it by adding testcontainers.reuse.enable=true to a file named .testcontainers.properties in your home directory (~/.testcontainers.properties). This keeps the container running between test executions, making subsequent runs much faster.
    • Warning: This is great for local work but should generally be disabled on CI servers to ensure a clean, isolated environment for every build.

The following video masterfully demonstrates diagnosing connection issues and then explores the container reuse feature in detail.

Testcontainers – From Zero to Hero. By @MarcoCodes

In this video, "Testcontainers – From Zero to Hero", Marco Behler walks through common pitfalls. Watching him debug is a great learning experience.

Watch two key segments: Diagnosing Connection Issues (25:26 - 33:40): He manually configures the connection using @DynamicPropertySource, hits the Connection refused error, and debugs it. This gives you deep insight into what @ServiceConnection does for you. Speeding Up Tests (45:33 - 50:35): He explains and implements the container reuse feature, demonstrating the dramatic speed improvement on subsequent test runs.


Conclusion

Congratulations! You have now implemented the most robust form of automated testing for a Spring Boot application. By combining @SpringBootTest with Testcontainers, you can verify your application's behavior from end-to-end against real, production-like dependencies. This is a skill highly valued in backend engineering roles.

Key Takeaways:

  • @SpringBootTest loads the full application context for comprehensive integration testing.
  • Testcontainers provides ephemeral Docker containers for real dependencies like databases, eliminating the gap between test and production environments.
  • The @ServiceConnection annotation (in Spring Boot 3.1+) is the modern, simple way to connect your application to a Testcontainer.
  • Full integration tests provide the highest level of confidence by verifying that all application layers (web, service, data) work together correctly.

Preview of the Next Lesson:

We have now thoroughly tested our backend application, from unit and slice tests to full integration tests. The backend is solid. In the next and final lesson of this course, we will switch gears and finally connect our frontend by building a minimal Next.js UI to perform user registration and login against the deployed EKS cluster. This will bring the entire system together, verifying the complete user flow from browser to database and back.