Chapter 4: Integration Tests
Introduction
Unit tests with mocks are fast but do not guarantee that components work together. Integration tests verify that Spring, JPA, and your database collaborate correctly.
🎯 Chapter Objectives
By the end of this chapter, you will know how to:
- ✅ Use @SpringBootTest
- ✅ Test repositories with @DataJpaTest
- ✅ Test controllers with @WebMvcTest
- ✅ Configure test profiles
- ✅ Use TestContainers (bonus)
1. @SpringBootTest
Full Integration Test
@SpringBootTest // ← Loads the full Spring context
class ApplicationIntegrationTest {
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@Test
void contextLoads() {
// Verifies that the application starts
assertNotNull(userService);
}
@Test
void shouldCreateAndFindUser() {
User user = userService.create("John", "john@test.com");
User found = userService.findById(user.getId());
assertEquals("John", found.getName());
}
}
@SpringBootTest Options
// Full context with web server
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class FullStackTest {
@LocalServerPort
private int port;
}
// Without web server (faster)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
class ServiceTest { }
// With specific configuration
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:testdb",
"logging.level.root=WARN"
})
class ConfiguredTest { }
2. @DataJpaTest
Repository Test
@DataJpaTest // ← Configures only JPA + H2
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Autowired
private TestEntityManager entityManager;
@Test
void shouldFindByEmail() {
// Arrange
User user = new User("John", "john@test.com");
entityManager.persistAndFlush(user);
// Act
Optional<User> found = userRepository.findByEmail("john@test.com");
// Assert
assertTrue(found.isPresent());
assertEquals("John", found.get().getName());
}
@Test
void shouldReturnEmptyWhenEmailNotFound() {
Optional<User> found = userRepository.findByEmail("unknown@test.com");
assertFalse(found.isPresent());
}
}
What @DataJpaTest Configures
@DataJpaTest includes:
├── In-memory H2 (by default)
├── Hibernate/JPA
├── TestEntityManager
├── Repositories
└── @Transactional (rollback after each test)
Does NOT include:
├── @Service
├── @Controller
├── Spring Security
└── Other components
Testing Custom Queries
@DataJpaTest
class ProductRepositoryTest {
@Autowired
private ProductRepository productRepository;
@Autowired
private TestEntityManager em;
@BeforeEach
void setUp() {
em.persist(new Product("Laptop", 1000.0, "Electronics"));
em.persist(new Product("Phone", 800.0, "Electronics"));
em.persist(new Product("Shirt", 50.0, "Clothing"));
em.flush();
}
@Test
void shouldFindByCategory() {
List<Product> electronics = productRepository.findByCategory("Electronics");
assertThat(electronics).hasSize(2);
}
@Test
void shouldFindByPriceRange() {
List<Product> products = productRepository.findByPriceBetween(100.0, 900.0);
assertThat(products)
.hasSize(1)
.extracting(Product::getName)
.containsExactly("Phone");
}
@Test
void shouldCountByCategory() {
long count = productRepository.countByCategory("Electronics");
assertEquals(2, count);
}
}
3. @WebMvcTest
Controller Test (without real service)
@WebMvcTest(UserController.class) // ← Tests only this controller
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean // ← Mocks the service
private UserService userService;
@Test
void shouldReturnUser() throws Exception {
// Arrange
when(userService.findById(1L))
.thenReturn(new User(1L, "John", "john@test.com"));
// Act & Assert
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"))
.andExpect(jsonPath("$.email").value("john@test.com"));
}
@Test
void shouldReturn404WhenUserNotFound() throws Exception {
when(userService.findById(anyLong()))
.thenThrow(new UserNotFoundException(999L));
mockMvc.perform(get("/api/users/999"))
.andExpect(status().isNotFound());
}
}
@MockBean vs @Mock
// @MockBean: For Spring tests (injected into the context)
@WebMvcTest
class ControllerTest {
@MockBean
private UserService userService; // Replaces the Spring bean
}
// @Mock: For pure unit tests (Mockito only)
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Mock
private UserRepository userRepository; // Simple Mockito mock
}
4. Test Profiles
application-test.properties
# src/test/resources/application-test.properties
# H2 Database
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
# Disable features
spring.flyway.enabled=false
spring.mail.host=localhost
Activate the Profile
@SpringBootTest
@ActiveProfiles("test") // ← Uses application-test.properties
class MyIntegrationTest {
// ...
}
@TestPropertySource Annotation
@SpringBootTest
@TestPropertySource(properties = {
"spring.jpa.show-sql=false",
"app.feature.enabled=true"
})
class OverriddenPropertiesTest {
// ...
}
5. @Transactional in Tests
Automatic Rollback
@SpringBootTest
@Transactional // ← Rollback after each test
class TransactionalTest {
@Autowired
private UserRepository userRepository;
@Test
void test1() {
userRepository.save(new User("John"));
assertEquals(1, userRepository.count());
}
@Test
void test2() {
// The DB is empty because test1 was rolled back
assertEquals(0, userRepository.count());
}
}
@DataJpaTest is @Transactional by Default
@DataJpaTest // ← Already @Transactional
class RepositoryTest {
// Automatic rollback after each test
}
6. Test with Initial Data
@Sql
@SpringBootTest
@Sql("/test-data.sql") // ← Executes before each test
class SqlDataTest {
// ...
}
@Test
@Sql(scripts = "/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
void testWithCleanup() {
// ...
}
@SqlGroup
@SpringBootTest
@SqlGroup({
@Sql("/schema.sql"),
@Sql("/test-data.sql")
})
class MultiSqlTest {
// ...
}
test-data.sql File
-- src/test/resources/test-data.sql
INSERT INTO users (id, name, email) VALUES (1, 'John', 'john@test.com');
INSERT INTO users (id, name, email) VALUES (2, 'Jane', 'jane@test.com');
INSERT INTO products (id, name, price) VALUES (1, 'Laptop', 1000.00);
7. TestContainers (Bonus)
Why?
H2 is convenient but different from PostgreSQL/MySQL. TestContainers launches real databases in Docker.
Configuration
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
Usage
@SpringBootTest
@Testcontainers
class PostgreSQLIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private UserRepository userRepository;
@Test
void shouldSaveToRealPostgres() {
User user = userRepository.save(new User("John", "john@test.com"));
assertNotNull(user.getId());
}
}
8. Spring Boot Test Slices
Summary
| Annotation | Loaded Context | Usage |
|---|---|---|
@SpringBootTest | Everything | Full integration tests |
@DataJpaTest | JPA + H2 | Repository tests |
@WebMvcTest | MVC + Security | Controller tests |
@JsonTest | Jackson | Serialization tests |
@RestClientTest | RestTemplate | REST client tests |
Combine with @MockBean
@DataJpaTest
@Import(UserService.class) // Import the service
class UserServiceWithRealDbTest {
@Autowired
private UserService userService;
@MockBean
private EmailService emailService; // External mock
@Test
void shouldSaveUser() {
// userService uses the real repository
// emailService is mocked
}
}
9. Summary
Key Annotations
| Annotation | Usage |
|---|---|
@SpringBootTest | Full context |
@DataJpaTest | JPA/Repository tests |
@WebMvcTest | Controller tests |
@MockBean | Mock in Spring context |
@ActiveProfiles | Test profile |
@Sql | SQL data |
@Transactional | Automatic rollback |
Choosing the Type of Test
┌─────────────────────────────────────────────┐
│ What to test? │
├──────────────────────┬──────────────────────┤
│ Repository │ @DataJpaTest │
│ Controller only │ @WebMvcTest │
│ Service with mocks │ @ExtendWith(Mockito) │
│ Full stack │ @SpringBootTest │
│ With real DB │ TestContainers │
└──────────────────────┴──────────────────────┘
🎯 Next Step
You know how to test repositories and services. Now, let's learn how to test the REST API in detail with MockMvc.