Integration Testing
integration testing integration tests verify that multiple layers work together — controller → service → repository → database. spring boot's test slices
Introduction
Integration tests verify that multiple layers work together — controller → service → repository → database. Spring Boot's test slices (@WebMvcTest, @DataJpaTest, @SpringBootTest) let you choose how much context to load.
Informative example
Test pyramid for a Spring Boot service:
// Unit test — fast, no Spring@Test void calculateTotal() { ... }// Slice test — JPA only@DataJpaTestclass OrderRepoTest {@Autowired OrderRepository repo;@Test void findByStatus() { ... }}// Full integration — entire context + Testcontainers@SpringBootTest(webEnvironment = RANDOM_PORT)class OrderApiIT {@Autowired TestRestTemplate rest;@Test void endToEnd() {var resp = rest.postForEntity("/api/orders", req, OrderDto.class);assertThat(resp.getStatusCode()).isEqualTo(CREATED);}}
Best practices
- Follow the test pyramid: many unit, some integration, few E2E.
- Use @Transactional on tests for auto-rollback (with caution).
- Profile tests: unit < 10ms, integration < 2s each.
Purpose of this lesson
Master Integration Testing so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Integration Testing.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Unit (70%)
Fast, isolated, Mockito — service logic.
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Integration Testing daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Integration Testing in one minute.
Q2When would you avoid Integration Testing?
Summary
In this lesson you learned Integration Testing — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.