Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 65

    Integration Testing

    Integration tests boot a slice (or all) of the Spring context against real collaborators.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Integration tests boot a slice (or all) of the Spring context against real collaborators. For Boot 3 Orders, Testcontainers supplies Postgres (and Redis/Kafka when needed) so CI exercises real SQL and transactions — not H2 fantasies that diverge from production.

    Combine @SpringBootTest, @AutoConfigureMockMvc or WebTestClient, and @DynamicPropertySource to point datasource URLs at the container. Use @WithMockUser or test JWT support for secured routes.

    These tests are slower than unit tests — run them in CI and locally before merges that touch persistence or HTTP wiring.

    This lesson closes the testing pyramid for TechLearningPRO Orders.

    Purpose of this lesson

    Write Spring Boot 3 integration tests for Orders using Testcontainers Postgres and MockMvc.

    Understanding the topic

    Real wiring + real DB beat mocked SQL for API confidence.

    • @SpringBootTest: full (or sliced) application context.
    • Testcontainers: ephemeral Postgres matching prod major version.
    • DynamicPropertySource: inject JDBC URL/user/password at runtime.
    • MockMvc / WebTestClient: HTTP-level assertions without a real port (unless you want one).
    • Security test support: @WithMockUser or JWT test utilities.

    Step-by-step explanation

    1. Add Testcontainers Postgres and JUnit Jupiter dependencies.
    2. Declare a static PostgreSQLContainer and map datasource properties dynamically.
    3. Write a create-order MockMvc test with a mocked/authenticated user.
    4. Run in CI with Docker available; fail the build on assertion errors.

    Informative example

    Orders API IT with Testcontainers Postgres.

    java
    @SpringBootTest
    @Testcontainers
    @AutoConfigureMockMvc
    class OrderApiIT {
    @Container
    static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16");
    @DynamicPropertySource
    static void props(DynamicPropertyRegistry r) {
    r.add("spring.datasource.url", pg::getJdbcUrl);
    r.add("spring.datasource.username", pg::getUsername);
    r.add("spring.datasource.password", pg::getPassword);
    }
    @Autowired MockMvc mvc;
    @Test
    @WithMockUser(roles = "USER")
    void createsOrder() throws Exception {
    mvc.perform(post("/api/v1/orders")
    .contentType(MediaType.APPLICATION_JSON)
    .content("""
    {"userId":1,"items":[{"productId":10,"qty":2}],"currency":"USD"}
    """))
    .andExpect(status().isCreated())
    .andExpect(jsonPath("$.status").value("PLACED"));
    }
    }

    Real-world use

    An Orders migration used a Postgres-only JSONB column. H2 tests stayed green; production failed on migrate. Switching integration tests to Testcontainers Postgres caught the drift in CI the same afternoon — TechLearningPRO made Postgres containers mandatory for persistence PRs.

    Security implications

    ITs often bypass or stub security — be explicit.

    • Prefer testing at least one authenticated and one forbidden path.
    • Do not hardcode production passwords into containers — Testcontainers defaults are fine.
    • Avoid shipping test profiles that disable security into prod artifacts.

    Best practices

    • Reuse containers via singleton/static patterns carefully in CI for speed.
    • Flyway/Liquibase should run in ITs the same way as prod.
    • Tag tests (@Tag("integration")) so developers can opt in locally.

    Common mistakes

    • Using H2 for 'integration' tests that need Postgres features.
    • Sharing mutable DB state across tests without cleanup or transactions.
    • Starting the full context for every tiny assertion — prefer focused ITs plus unit tests.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy Testcontainers over H2?+

    Answer

    Same engine as production — catches SQL dialect, JSON, and constraint issues H2 misses.
    2IntermediateQuestionWhat does @DynamicPropertySource do?+

    Answer

    Registers connection properties from the running container before the context refreshes.
    3BeginnerQuestionWhere do integration tests sit in the pyramid?+

    Answer

    Fewer than unit tests, slower, higher confidence on wiring, HTTP, SQL, and security filters.

    Hands-on exercise

    Lab. Run the IT above against Postgres 16. Add a second test that expects 403 for a user without ROLE_USER. Confirm Flyway migrations applied inside the container.

    Summary

    Integration tests prove Orders works as a system. Next: why teams split that system into microservices.

    Ready to mark this lesson complete?Track your journey across the entire course.