Integration Testing
Integration tests boot a slice (or all) of the Spring context against real collaborators.
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:
@WithMockUseror JWT test utilities.
Step-by-step explanation
- Add Testcontainers Postgres and JUnit Jupiter dependencies.
- Declare a static
PostgreSQLContainerand map datasource properties dynamically. - Write a create-order MockMvc test with a mocked/authenticated user.
- Run in CI with Docker available; fail the build on assertion errors.
Informative example
Orders API IT with Testcontainers Postgres.
@SpringBootTest@Testcontainers@AutoConfigureMockMvcclass OrderApiIT {@Containerstatic PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16");@DynamicPropertySourcestatic 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.
1BeginnerQuestionWhy Testcontainers over H2?+
Answer
2IntermediateQuestionWhat does @DynamicPropertySource do?+
Answer
3BeginnerQuestionWhere do integration tests sit in the pyramid?+
Answer
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.