Sub topic 3
Testing Spring Boot Applications Beyond Unit Tests
Assume you know Java, JUnit, dependency injection, REST controllers, and Spring Data JPA. This chapter focuses on integration tests: tests that combine application code with real infrastructure or Spring configuration.
Test a real database with Testcontainers
Testcontainers starts disposable services in containers for a test. A repository test can therefore use PostgreSQL instead of an in-memory database.
@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class GreetingRepositoryTest {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16");
@Autowired
GreetingRepository repository;
@Test
void findsGreetingByName() {
repository.save(new Greeting("Ada", "Hello, Ada"));
assertThat(repository.findByName("Ada")).isPresent();
}
}DataJpaTest loads the JPA layer. ServiceConnection connects Spring Boot to the container. The test database is usually reset between tests.
Run full-stack HTTP tests
Use SpringBootTest with a random port when you need to test application startup, routing, serialization, security, and persistence together.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class GreetingApiTest {
@Autowired
TestRestTemplate restTemplate;
@Test
void healthEndpointIsUp() {
ResponseEntity<String> response =
restTemplate.getForEntity("/actuator/health", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}The random port prevents conflicts between parallel test runs. TestRestTemplate resolves relative URLs against that port.
Test security and other boundaries
Spring Security’s test support can add an authenticated user to a MockMvc request:
mockMvc.perform(get("/greetings/Ada").with(user("ada")))
.andExpect(status().isOk());Use JsonTest for JSON serialization and deserialization. Use RestClientTest for HTTP client code. These slices load focused configuration instead of the whole application.
Understand context caching
Spring caches application contexts between tests when their configuration matches. Different profiles, properties, mock beans, or configuration classes create different cache entries. Excessive variation causes repeated startup and slows the suite.
Keep the suite reliable
- Prefer unit tests for business rules.
- Use slices for controllers, repositories, JSON, and clients.
- Use full-context tests for a few critical workflows.
- Keep Testcontainers data isolated and deterministic.
- Avoid timing assumptions and shared mutable state.
- Run the same tests in CI with the required container runtime.
Exercise
Which test type is appropriate for verifying a repository query against PostgreSQL?
Show answer
Use DataJpaTest with Testcontainers and ServiceConnection.