Spring Boot: From Basics to Production · Testing Spring Boot Applications

Full Integration Tests with @SpringBootTest

Test the whole application through HTTP with real infrastructure.

@SpringBootTest(webEnvironment = RANDOM_PORT) starts the complete app on a random port; call it with TestRestTemplate, RestClient or WebTestClient. Back it with Testcontainers for databases and brokers (shared via a @TestConfiguration with @ServiceConnection beans), and stub external HTTP services with WireMock. Keep these tests few and focused on critical flows; Spring caches contexts between tests with identical configuration.

@TestConfiguration(proxyBeanMethods = false)
class TestcontainersConfig {
    @Bean
    @ServiceConnection
    PostgreSQLContainer<?> postgres() {
        return new PostgreSQLContainer<>("postgres:17-alpine");
    }
}

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Import(TestcontainersConfig.class)
class CheckoutFlowIT {
    @Autowired TestRestTemplate http;
    @MockitoBean PaymentGateway payments;      // external service stubbed

    @Test
    void customerCanCheckOut() {
        when(payments.charge(any(), any())).thenReturn(new PaymentResult("pay_1"));
        var response = http.postForEntity("/api/v1/checkout", new CheckoutRequest("cart-1", "tok"), OrderResponse.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
    }
}

Common pitfalls

  • Many slightly different contexts (each @MockitoBean combination creates a new cached context).
  • Real calls to third-party APIs in tests.
  • Hundreds of full-context tests making CI slow.

Key points

  • @SpringBootTest for end-to-end flows
  • Testcontainers + WireMock/mocks for externals
  • Reuse cached contexts

Further reading: Spring Boot: Testing applications

Practice questions

Why can many @SpringBootTest classes make the suite slow?

Answer

Each distinct configuration (different mocked beans, properties or profiles) requires a new application context; reusing identical configurations lets Spring's context cache help.

Since Spring Boot 3.1, how can you use Testcontainers during local development too?

Answer

Define containers as @ServiceConnection beans in a test configuration and run the app with a TestApplication main (SpringApplication.from(...).with(...)), so ./mvnw spring-boot:test-run starts dependencies automatically.

Open in the app to mark lessons complete, take notes and track your progress.