Integration Tests: The Whole Stack

Integration Tests: The Whole Stack in Java: Unit tests prove a class works in isolation. They cannot prove your JSON mapping is right, your SQL is valid, or…

Concept Explanation

Unit tests prove a class works in isolation. They cannot prove your JSON mapping is right, your SQL is valid, or your security rules apply. For that you need to start (part of) the real application.

Spring Boot gives you three levels, from cheap to expensive:

AnnotationStartsSpeed
@WebMvcTestweb layer only, services mockedfast
@DataJpaTestJPA + in-memory databasefast
@SpringBootTestthe whole applicationslow

Testing a Controller Alone

@WebMvcTest(ProductController.class)
class ProductControllerTest {

    @Autowired MockMvc mvc;
    @MockBean  ProductService service;      // the real service is replaced

    @Test
    void returnsProductAsJson() throws Exception {
        when(service.byId(1L)).thenReturn(new Product(1L, "Pen"));

        mvc.perform(get("/api/products/1"))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.name").value("Pen"));
    }

    @Test
    void rejectsInvalidBody() throws Exception {
        mvc.perform(post("/api/products")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"name\":\"\"}"))
           .andExpect(status().isBadRequest());
    }
}

No server socket is opened, but routing, JSON serialisation, and validation are all genuinely exercised.


Testing Repositories

@DataJpaTest
class ProductRepositoryTest {

    @Autowired ProductRepository repo;

    @Test
    void findsByNameFragment() {
        repo.save(new Product("Blue Pen"));
        repo.save(new Product("Red Book"));

        List<Product> found = repo.findByNameContainingIgnoreCase("pen");

        assertEquals(1, found.size());
    }
}

Each test runs in a transaction that is rolled back afterwards, so tests cannot pollute each other.


The Full Application

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class ProductApiIT {

    @Autowired TestRestTemplate rest;

    @Test
    void createThenFetch() {
        ResponseEntity<Product> created = rest.postForEntity(
            "/api/products", new CreateProductRequest("Lamp", TEN), Product.class);

        assertEquals(HttpStatus.CREATED, created.getStatusCode());

        Product fetched = rest.getForObject(
            "/api/products/" + created.getBody().getId(), Product.class);

        assertEquals("Lamp", fetched.getName());
    }
}

Real Databases with Testcontainers

An in-memory H2 database does not behave like production PostgreSQL. Testcontainers runs the real thing in Docker:

@SpringBootTest
@Testcontainers
class RealDbIT {

    @Container
    static PostgreSQLContainer<?> db =
        new PostgreSQLContainer<>("postgres:16");

    @DynamicPropertySource
    static void props(DynamicPropertyRegistry r) {
        r.add("spring.datasource.url", db::getJdbcUrl);
        r.add("spring.datasource.username", db::getUsername);
        r.add("spring.datasource.password", db::getPassword);
    }
}

Common Mistakes

  1. @SpringBootTest for everything: Starting the full context per test class turns a 5-second suite into 5 minutes. Use the narrowest slice.
  2. Tests that depend on order: Each test must set up its own data and assume nothing.
  3. Hitting real external APIs: Your suite then fails when someone else's server is down. Use WireMock.
  4. H2 in tests, PostgreSQL in production: Dialect differences hide real bugs until deployment.

Best Practices

  • Shape the suite like a pyramid: many unit tests, some slice tests, a few end-to-end tests.
  • Name integration tests *IT so the build can run them in a separate, slower phase.
  • Assert on status codes and JSON structure, not on log output.
  • Use @ActiveProfiles("test") to keep test configuration clearly separate.

Practice Exercises

  1. The Slice: Write a @WebMvcTest that asserts a 400 response for an invalid request body, with the service mocked out.
  2. The Rollback: Save a row in a @DataJpaTest, then confirm in a second test that the row is gone.
  3. The Round Trip: Use @SpringBootTest with TestRestTemplate to POST then GET the same resource.